Post.all.map(&:id) 是什么意思? [英] What does Post.all.map(&:id) mean?

查看:16
本文介绍了Post.all.map(&:id) 是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
map(&:name) 在 Ruby 中是什么意思?

Post.all.map(&:id) 

会回来

 => [1, 2, 3, 4, 5, 6, 7, ................] 

map(&:id) 是什么意思?尤其是&.

What does map(&:id) mean? Especially the &.

推荐答案

& 符号用于表示应将以下参数视为赋予方法的块.这意味着如果它还不是 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.

这篇关于Post.all.map(&:id) 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆