Possible Duplicates:
Ruby/Ruby on Rails ampersand colon shortcut
What does map(&:name) mean in Ruby?
I was reading Stackoverflow and stumbled upon the following code
array.map(&:to_i)
Ok, it's easy to see what this code does but I'd like to know more about &:
construct which I have never seen before.
Unfortunately all I can think of is "lambda" which it is not. Google tells me that lambda syntax in Ruby is ->->(x,y){ x * y }
So anyone knows what that mysterious &:
is and what it can do except calling a single method?
There's a few moving pieces here, but the name for what's going on is the
Symbol#to_proc
conversion. This is part of Ruby 1.9 and up, and is also available if you use later-ish versions of Rails.First, in Ruby,
:foo
means "the symbolfoo
", so it's actually two separate operators you're looking at, not one big&:
operator.When you say
foo.map(&bar)
, you're telling Ruby, "send a message to thefoo
object to invoke themap
method, with a block I already defined calledbar
". Ifbar
is not already aProc
object, Ruby will try to make it one.Here, we don't actually pass a block, but instead a symbol called
bar
. Because we have an implicitto_proc
conversion available onSymbol
, Ruby sees that and uses it. It turns out that this conversion looks like this:This makes a
proc
which invokes the method with the same name as the symbol. Putting it all together, using your original example:This invokes
.map
on array, and for each element in the array, returns the result of callingto_i
on that element.