Can you supply arguments to the map(&:method) syntax in Ruby?

后端 未结 7 1240
面向向阳花
面向向阳花 2020-11-22 16:59

You\'re probably familiar with the following Ruby shorthand (a is an array):

a.map(&:method)

For example, try the followin

7条回答
  •  鱼传尺愫
    2020-11-22 17:47

    For your example can be done a.map(&2.method(:+)).

    Arup-iMac:$ pry
    [1] pry(main)> a = [1,3,5,7,9]
    => [1, 3, 5, 7, 9]
    [2] pry(main)> a.map(&2.method(:+))
    => [3, 5, 7, 9, 11]
    [3] pry(main)> 
    

    Here is how it works :-

    [3] pry(main)> 2.method(:+)
    => #
    [4] pry(main)> 2.method(:+).to_proc
    => #
    [5] pry(main)> 2.method(:+).to_proc.call(1)
    => 3
    

    2.method(:+) gives a Method object. Then &, on 2.method(:+), actually a call #to_proc method, which is making it a Proc object. Then follow What do you call the &: operator in Ruby?.

提交回复
热议问题