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 map() of enumerable is an inbuilt method in Ruby returns a new array with the results of running block once for every element in enum. The object is repeated every time for each enum. In case no object is given, it return nil for each enum.
Map is a Ruby method that you can use with Arrays, Hashes & Ranges. The main use for map is to TRANSFORM data. For example: Given an array of strings, you could go over every string & make every character UPPERCASE.
The way the map method works in Ruby is, it takes an enumerable object, (i.e. the object you call it on), and a block. Then, for each of the elements in the enumerable, it executes the block, passing it the current element as an argument. The result of evaluating the block is then used to construct the resulting array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With