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

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.

Leave a Comment

deneme bonusudeneme bonusu veren sitelerOnwin Güncel Giriştürkçe altyazılı pornocanlı bahis casino