Question
This question already has answers here :
[What does map(&:name) mean in Ruby?](/questions/1217088/what-does-mapname- mean-in-ruby) (17 answers)
Closed 9 years ago.
I saw the code from [here](http://edgerails.info/articles/what-s-new-in-edge- rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/)
Post.published.collect(&:views_count)
I guess it equals to
.collect { |p| p.views_count }
But I never saw this usage before, does this have a name? Where can I find more information about it?
Answer
This is actually a rather clever hack made it into ruby 1.9.
Basically, &
in front of a variable in ruby coerces it into a proc. It does
that by calling to_proc
. Some clever fellow (first time I saw this was in
_whys code, but I won't credit him cause I don't know if he came up with it)
added a to_proc
method to Symbol
, that is essentially {|obj| obj.send self}
.
There aren't many coercians in ruby, but it seems like all of them are mostly used to do hacks like this (like !! to coerce any type into a boolean)