Hi,
as you probably 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.
However, I don’t seem to be able 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 & is only available on a method call, such as arr.map(&:upcase)
. Why??