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
Now let’s play with the class just defined:
1 2 3 4
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
Now, if we play with this code like in the example above, the result is the following:
1 2 3
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!