Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Post.all.map(&:id) mean? [duplicate]

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 &.

like image 347
hey mike Avatar asked Feb 27 '12 16:02

hey mike


People also ask

What does MAP mean in Ruby?

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.

What does map do in Rails?

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.

How does Ruby map work?

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.


1 Answers

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.

like image 54
Niklas B. Avatar answered Sep 28 '22 08:09

Niklas B.