as you might know, Ruby has a shorthand operator &
which let's us easily convert a Symbol
to a Proc
. Example:
%w(a b c).map(&:upcase) #=> ["A", "B", "C"]
Would be equivalent to:
%w(a b c).map { |c| c.upcase } #=> ["A", "B", "C"]
And the explanation is that &:upcase
is calling to_proc
on :upcase
to create a Proc
object.
So, that pretty much explains what the operator does when it's used as the last argument of a method.
However, looks like it's not possible to use the operator anywhere outside the params of a method call:
:upcase.to_proc => #<Proc:0x007febbc85ab38(&:upcase)>
&:upcase => SyntaxError: syntax error, unexpected &
This would have been nice to use like this:
case number
when &:even?
# ...
when &:prime?
# ...
end
This works though:
case number
when :even?.to_proc
# ...
when :prime?.to_proc
# ...
end
In short, the unary operator &
can only be used in the arguments of a method, for example in arr.map(&:upcase)
. What is the reason for that?