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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With