Ruby映射方法语法问题
我正在观看railscasts 更多虚拟属性剧集。在那一集中,瑞安一度使用了一种我无法理解的映射方法语法,有人可以解释一下吗?
tags.map(&:name).join(' ')
Tags是Tag Model的一个对象,它有一个name属性。我能够理解这句话的意思(我想是的:))。所有标记对象的名称属性都以数组形式检索并基于“ ”进行连接。但是 &:name
是怎么回事
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
&
是Symbol#to_proc
的快捷方式,它将把传递给它的符号转换为对象上的方法名称。因此&:name
转换为{ |reciever| receiveiever.name }
然后传递给 map 方法。这是使代码更加简洁并避免到处都有大量块的好方法。
The
&
is a shortcut toSymbol#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.
它是
tags.map(:name.to_proc)
的简写,就像调用tags.map{|tag| tag.name }
并将所有标签名称收集到一个数组中。It's shorthand for
tags.map(:name.to_proc)
which is like callingtags.map{|tag| tag.name }
and just collects all the tag names into an array.