What does map(&:name) do in this Ruby code?

前端 未结 1 1614
北海茫月
北海茫月 2020-11-27 07:50

Trying to understand Ruby a bit better, I ran into this code surfing the Internet:

require \'rubygems\'
require \'activeresource\'



ActiveResource::Base.lo         


        
相关标签:
1条回答
  • 2020-11-27 08:08
    events.map(&:name)
    

    is exactly equivalent to

    events.map{|x| x.name}
    

    it is just convenient syntactic sugar.

    For more details, check out the Symbol#to_proc method here. Here, :name is being coerced to a proc.

    By the way, this comes up often here - it's just very hard to google or otherwise search for 'the colon thing with an ampersand' :).

    0 讨论(0)
提交回复
热议问题