One property of the Ruby object model and object oriented programming in general is that a subclass of an object automatically inherits all of the methods of its superclass. Classes can further expand the number of methods available by mixing in a Module, or several.
Because of mixins and subclassing even a class that has declared just a few methods can actually have hundreds of methods on it. In Ruby, all classes subclass Object by default which declares a hefty 45 methods, guaranteeing you to have at least that many. Out of the box in 1.8.7, a Ruby String object has 176 instance methods. If you are programming on top of the Rails framework, ActiveSupport adds 98 methods bringing the total to 274!
On numerous occasions I have needed to see what methods are available on an object I am working with I will type the following in irb
.
myobject.methods - Object.instance_methods
This prints out a large array of instance methods with the methods inherited from Object removed from the list. This is useful but what if the object I am working with mixed in several modules and I am left with a list of over a hundred methods? It would be great to view which Class or Module each method came from. Well, actually there’s a gem for that.™
Looksee
Looksee is a new gem by George Ogata that examines the method lookup path of any object. To use it add require 'looksee/shortcuts'
to your ~/.irbrc
. This will add a lp
(”lookup path”) method to your irb environment. When passed an object lp
prints out a colored display showing where each of an object’s methods lives.
- public methods are show in green
- protected methods are show in yellow
- private methods are show in red
- overwritten methods are show in gray
Go ahead and install Looksee and play around with it for a moment. Run lp
on a String in vanilla irb and then open script/console
in a Rails project and do the same thing. It is quite eye-opening to see the additions that the Rails framework makes.
About the Author