Ruby map method syntax issue

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

I watched railscasts for more episodes of virtual attributes . In this episode, at some point, Ryan used the syntax of the map method, which I cannot understand, can anyone explain this?

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

is a Model tag that has a name attribute. I can understand the meaning of this (I think so :)). All attributes of the tag object name are retrieved as an array and merged based on. '' But what is the deal with &:name

thanks

+3
source share
2 answers

& is the shortcut for Symbol#to_proc , which converts the character you pass it to the method name on the object. Therefore, &:name converted to { |reciever| receiever.name } { |reciever| receiever.name } , which is then passed to the map method.

This is a great way to make your code much more concise and avoid having many blocks all over the place.

+9
source

This is an abbreviation for tags.map(:name.to_proc) , which is like calling tags.map{|tag| tag.name } tags.map{|tag| tag.name } and just collects all the tag names into an array.

+6
source

Source: https://habr.com/ru/post/1446044/


All Articles