The (&:even?)
syntax in Ruby is a shorthand for calling the even?
method on each element of an array or collection.
For example, suppose we have an array of numbers [1, 2, 3, 4, 5]
and we want to select only the even numbers. We can achieve this using the select
method and the (&:even?)
syntax:
main.rb65 chars3 lines
This is equivalent to:
main.rb82 chars3 lines
So, (&:even?)
replaces the block that would be passed to the select
method and calls the even?
method on each element.
This shorthand syntax can only be used with methods that take a single argument and don't have any side-effects. So, you cannot use (&:)
everywhere as an iterator. It is specific to certain methods that expect a block.
However, you can use it with other iterator methods like map
, reduce
, and each
, as long as the method you are calling on each element satisfies the criteria mentioned above.
main.rb282 chars7 lines
In summary, (&:even?)
is a shorthand syntax to call a method on each element of an array or collection, and it can be used with certain iterator methods that expect a block.
gistlibby LogSnag