Home > Software design >  How to pass a string method in a map call?
How to pass a string method in a map call?

Time:07-13

I want to write this ["foo", "bar"].map {|x| x.capitalize} as something like this ["foo", "bar"].map(&method(:String.capitalize))

To be more precise, given a list L of instances of C and an instance method M I want to call M on each element of L as element.M, in a point-free maner

CodePudding user response:

What you're looking for is ["foo", "bar"].map(&:capitalize).

How does this work?

:capitalize is a just a plain ol' ruby symbol. The magic item here is the ampersand which can be used as a prefix to a method argument; the & automatically invokes to_proc on the item that it prefixes:

x = test(&Bar) # call Bar.to_proc

To put it all together, the implementation of to_proc on Symbol returns a proc that invokes the method with the given name; something like:

class Symbol
  def to_proc
    Proc.new { |object, *args| object.send(self, *args) }
  end
end
  •  Tags:  
  • ruby
  • Related