Zhu Wu's Blog

The world is a fine place and worth fighting for.

Debugging Ruby Methods at Runtime

Due to the dynamic nature of Ruby, it is hard to locate a method definition statically. Thus, we can only find the method definition accurately at runtime. Here are some tips.

Suppose we have an object called foo. We can use foo.methods to find which methods are available for this object. However, calling foo.methods may get a long method list. To avoid this, we can filter the ones we are interested in by a regular expression. For example, we can call foo.methods.grep(/bar/) to find all the foo's methods whose names contain the word bar.

If we want to further inspect the method bar of object foo. We can find which class defines the method bar by calling foo.method(:bar).owner. To find the location of the file which defines the method, we can call foo.method(:bar).source_location. The source_location returns the source code location and the line number of the method.

To investigate the calling stack of the method bar, we can print the calling stack out by calling puts caller in the method body of bar.