Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - what does Array.any?(&:nil?) mean?

Tags:

ruby

I am new to ruby and working through a tutorial but am not sure what this line of code means:

[movie, version_number].any?(&:nil?)

From my research, Array.any? returns true if any of the elements of the array are not false or nil. And &:nil? means to call to_proc() on the symbol :nil? i.e. :nil?.to_proc so the statement is equivalent to

[movie, version_number].any?(:nil?.to_proc)

which is equivalent to

[movie, version_number].any?{|item| item.nil?}

Further, any? Passes each element of the collection (in this case, Array) to the {|item| item.nil?} block.

When you put them together, does the line of code mean, call nil? on each element in the Array before calling .any? on the array, i.e. is it equivalent to:

[movie.nil?, version_number.nil?].any?

Or, in plain English, are any of movie or version_number equivalent to nil?

like image 659
Kevin L. Avatar asked Feb 11 '18 08:02

Kevin L.


People also ask

What does array mean in Ruby?

An array is a data structure that represents a list of values, called elements. Arrays let you store multiple values in a single variable. In Ruby, arrays can contain any data type, including numbers, strings, and other Ruby objects. This can condense and organize your code, making it more readable and maintainable.

What does any do in Ruby?

The any?() of enumerable is an inbuilt method in Ruby returns a boolean value if any of the object in the enumerable satisfies the given condition, else it returns false. Parameters: The function takes two types of parameters, one is the object and the block, while the other is the pattern.

What does .first mean in Ruby?

Ruby | Array class first() function first() is a Array class method which returns the first element of the array or the first 'n' elements from the array.

What does .index do in Ruby?

index is a String class method in Ruby which is used to returns the index of the first occurrence of the given substring or pattern (regexp) in the given string. It specifies the position in the string to begin the search if the second parameter is present. It will return nil if not found.


1 Answers

From Symbol#to_proc documentation:

Returns a Proc object which respond to the given method by sym.

(1..3).collect(&:to_s)  #=> ["1", "2", "3"] 

So in your case this is effectively the same as writing:

[movie, version_number].any?{|item| item.nil? }

any? expects a block[1] to be passed, which will be evaluated for each item, and will return true if the block evaluates to true for any of the members.

The to_proc method on Symbol is basically a convenience shortcut, when you just want to call a single method on the item passed to the block. As in the example above, this leads to shorter code than explicitly defining the block.

[1] Refer this article on blocks, procs and lambdas in ruby

like image 155
lorefnon Avatar answered Oct 07 '22 15:10

lorefnon