Ruby map method syntax question [duplicate]

一个人想着一个人 提交于 2019-12-30 05:07:45

问题


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


回答1:


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.




回答2:


It's shorthand for tags.map(:name.to_proc) which is like calling tags.map{|tag| tag.name } and just collects all the tag names into an array.



来源:https://stackoverflow.com/questions/5231919/ruby-map-method-syntax-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!