I saw the code from here
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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 callingto_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 ato_procmethod toSymbol, 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)