且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Post.all.map(&:id) 是什么意思?

更新时间:2023-01-24 12:45:27

& 符号用于表示应将以下参数视为赋予方法的块.这意味着如果它还不是 Proc 对象,它的 to_proc 方法将被调用以将其转换为一个.

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)

又等价于

Post.all.map { |x| x.id }

因此它遍历由 Post.all 返回的集合,并使用对每个项目调用的 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.

这是可行的,因为 Symbol#to_proc 创建了一个 Proc,它接受一个对象并调用带有符号名称的方法.主要是为了方便,节省一些打字的时间.

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.