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

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

问题描述

  

可能重复:
  什么地图(安培;:名)是指在Ruby中

  Post.all.map(安培;:ID)
 

返回

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

这是什么地图(安培;:ID)是什么意思?尤其是&安培;

解决方案

&安培; 符号用来表示下列参数应被视为给予块该方法。这意味着,如果它不是一个Proc对象,但它的 to_proc 方法将被调用把它改造成一个。

因此​​,你的榜样,会导致类似

  Post.all.map(安培;:id.to_proc)
 

这又相当于

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

因此​​,它遍历由 Post.all 返回的集合,并建立与 ID的结果数组要求每一个项目的方法。

这工作,因为 符号#to_proc 创建一个Proc的需要一个对象,并调用该方法与它的符号的名称。它主要用于方便,节省一些打字。

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

解决方案

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.

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

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