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

后端 未结 16 2534
时光取名叫无心
时光取名叫无心 2020-11-21 05:34

I found this code in a RailsCast:

def tag_names
  @tag_names || tags.map(&:name).join(\' \')
end

What does the (&:name)

16条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-21 05:54

    While let us also note that ampersand #to_proc magic can work with any class, not just Symbol. Many Rubyists choose to define #to_proc on Array class:

    class Array
      def to_proc
        proc { |receiver| receiver.send *self }
      end
    end
    
    # And then...
    
    [ 'Hello', 'Goodbye' ].map &[ :+, ' world!' ]
    #=> ["Hello world!", "Goodbye world!"]
    

    Ampersand & works by sending to_proc message on its operand, which, in the above code, is of Array class. And since I defined #to_proc method on Array, the line becomes:

    [ 'Hello', 'Goodbye' ].map { |receiver| receiver.send( :+, ' world!' ) }
    

提交回复
热议问题