Ruby Map方法语法问题 [英] Ruby map method syntax question

查看:193
本文介绍了Ruby Map方法语法问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我正在观看用更多的虚拟属性来插播.在那集中,ryan曾经使用一种我无法理解的map方法语法,有人可以解释一下吗?

tags.map(&:name).join(' ')

tags是标签模型的对象,它具有名称属性.我能够理解这个含义(我是这样认为的)).所有标记对象的name属性都作为数组检索,并基于''进行连接.但是&:name

有什么用呢?

谢谢

&Symbol#to_proc的快捷方式,它将把您传递给它的符号转换为该对象上的方法名称.因此,&:name转换为{ |reciever| receiever.name },然后将其传递给map方法.

这是使您的代码更加简洁并避免在各处放置大量块的好方法.

Possible Duplicate:
What does map(&:name) mean in Ruby?

I was watching railscasts more virtual attributes episode. In that episode, at one point, ryan used a map method syntax which I am not able to understand, Could someone please explain it?

tags.map(&:name).join(' ')

tags is an object of Tag Model, which has a name attribute. I am able to understand the meaning of this(I think so :)). All the tag object's name attribute are retrieved as an array and joined based on the ' '. But whats the deal with &:name

Thanks

解决方案

The & is a shortcut to Symbol#to_proc which will convert the symbol you pass to it to a method name on the object. So &:name converts to { |reciever| receiever.name } which is then passed to the map method.

It's a great way to make your code a lot more concise and avoid having tons of blocks all over the place.

这篇关于Ruby Map方法语法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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