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 &
.
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 &
.
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, its to_proc
method will be called to transform it into one.
Thus, your example results in something like
Post.all.map(&:id.to_proc)
which in turn is equivalent to
Post.all.map { |x| x.id }
So it iterates over the collection returned by Post.all
and builds up an array with the result of the id
method called on every item.
This works because Symbol#to_proc
creates 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.
& means that you are passing a block
Post.all is the receiver of the method .map, and its block is being passed on
Post.all.map { |item| # do something }
http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-map
It iterates over the array and create a lambda with symbol#to_proc
This takes all Post
objects and creates an array with the id
method being invoked on each one.
In other words, for ActiveRecord, this means that you are getting an array with the id
attribute for all Post
entities in your database.
It is a Ruby trick, which relies on Ruby doing some dynamic type conversion. You can find an explanation of the Symbol#to_proc trick here.