Possible Duplicate:
What does map(&:name) mean in Ruby?
Post.all.map(&:id)
will return
=> [1, 2, 3, 4, 5, 6, 7, ................]
What does map(&:id) mean? Especially the &.
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.
The
&symbol is used to denote that the following argument should be treated as the block given to the method. That means that if it’s not a Proc object yet, itsto_procmethod will be called to transform it into one.Thus, your example results in something like
which in turn is equivalent to
So it iterates over the collection returned by
Post.alland builds up an array with the result of theidmethod called on every item.This works because
Symbol#to_proccreates a Proc that takes an object and calls the method with the name of the symbol on it. It’s mainly used for convenience, to save some typing.