Ruby-on-rails Post.all.map(&:id) 是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9468564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does Post.all.map(&:id) mean?
提问by hey mike
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 &.
什么map(&:id)意思?尤其是&.
回答by Niklas B.
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_procmethod will be called to transform it into one.
该&符号用于表示应将以下参数视为赋予该方法的块。这意味着如果它还不是 Proc 对象,to_proc则将调用其方法将其转换为一个。
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.alland builds up an array with the result of the idmethod called on every item.
因此,它遍历 返回的集合Post.all并构建一个数组,其中包含id对每个项目调用的方法的结果。
This works because Symbol#to_proccreates 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.
这是有效的,因为Symbol#to_proc创建了一个 Proc,它接受一个对象并调用带有符号名称的方法。它主要用于方便,以节省一些打字。
回答by Andre Dublin
& means that you are passing a block
& 意味着你正在传递一个块
Post.all is the receiver of the method .map, and its block is being passed on
Post.all 是 .map 方法的接收者,并且它的块正在被传递
Post.all.map { |item| # do something }
http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-map
http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-map
It iterates over the array and create a lambda with symbol#to_proc
它遍历数组并使用符号#to_proc 创建一个 lambda
回答by Platinum Azure
This takes all Postobjects and creates an array with the idmethod being invoked on each one.
这将获取所有Post对象并创建一个数组,并id在每个对象上调用该方法。
In other words, for ActiveRecord, this means that you are getting an array with the idattribute for all Postentities in your database.
换句话说,对于 ActiveRecord,这意味着您将获得一个包含数据库中id所有Post实体的属性的数组。
回答by 0x4a6f4672
It is a Ruby trick, which relies on Ruby doing some dynamic type conversion. You can find an explanation of the Symbol#to_proc trick here.
这是一个 Ruby 技巧,它依赖于 Ruby 进行一些动态类型转换。您可以在此处找到Symbol#to_proc 技巧的说明。

