Ruby method objects

If we want to capitalise all the values in an array, we can use #map.

1
2
["apple", "pear", "banana"].map { |fruit| fruit.upcase }
=> ["APPLE", "PEAR", "BANANA"]

Alternatively, a more terse version is available using the Symbol#to_proc trick.

1
2
["apple", "pear", "banana"].map(&:upcase)
=> ["APPLE", "PEAR", "BANANA"]

We can even achieve the same thing using an explicit Proc object.

1
2
["apple", "pear", "banana"].map(&Proc.new { |fruit| fruit.upcase })
=> ["APPLE", "PEAR", "BANANA"]

But, I wanna call my own method!

But what if you want to call a method of your own creation?

In Ruby, methods are not objects. They are one of the few things in Ruby that aren't. That's why we have the Object#method method.

We need to get an object instance which we can pass to #map.

1
2
3
4
5
6
7
8
class Foo
  def self.bar(value)
    value.upcase
  end
end

["apple", "pear", "banana"].map(&Foo.method(:bar))
=> ["APPLE", "PEAR", "BANANA"]

We first get an instance of the .bar method using Foo.method and then the Method object is converted to a block using & and applied to every item in the array.