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

后端 未结 7 1202
面向向阳花
面向向阳花 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:53

    There is another native option for enumerables which is pretty only for two arguments in my opinion. the class Enumerable has the method with_object which then returns another Enumerable.

    So you can call the & operator for a method with each item and the object as arguments.

    Example:

    a = [1,3,5,7,9]
    a.to_enum.with_object(2).map(&:+) # => [3, 5, 7, 9, 11]
    

    In the case you want more arguments you should repeat the proccess but it's ugly in my opinion:

    a = [1,3,5,7,9]
    a.to_enum.with_object(2).map(&:+).to_enum.with_object(5).map(&:+) # => [8, 10, 12, 14, 16]
    

提交回复
热议问题