Davide Targa website

Programming, web development and open source

Get the Name of the Caller Method in Ruby

Sometimes, inside a ruby method may be useful to know which method was the caller. In other words you may want to know which method called another method. To do so, Ruby defines the caller method which returns some useful information about the method that called the current one.

For example, let’s say we have the following simple class:

1
2
3
4
5
6
7
8
9
class Myclass
  def foo
    bar
  end

  def bar
    puts "I was called from #{caller[0]}
  end
end

Now let’s play with the class just defined:

1
2
3
4
a = Myclass.new
a.foo
I was called from (irb):130:in `foo'
=> nil

As we can see, the bar method tells us that it was called from the foo method at line x of our irb session. To clean up things we can use a regular expression inside the puts of the bar method. Let’s say we want the puts to return only the name of the caller method. We can reopen the class and redefine the bar method in this way:

1
2
3
4
5
class Myclass
  def bar
    puts "I was called from #{caller[0][/`.*'/][1..-2]}
  end
end

Now, if we play with this code like in the example above, the result is the following:

1
2
3
a.foo
I was called from foo
=> nil

In this way, we can use the caller method inside bar to perform conditional choices based on the name of the caller method.

Enjoy with Ruby!

Comments