Interesting Object Methods in Ruby

This little Rubyism is something that I use frequently for debugging my objects. I add a method to every object to show only the interesting methods. What do I mean by interesting methods?

In my .irbrc file, I have the following lines of code:

class Object
  def i_methods
    (self.methods - Object.new.methods).sort
  end
end

Using the Ruby notion that classes are always open, it opens up the base class Object (of which almost everything in Ruby inherits) and adds a method called i_methods. This shows all methods available on the object minus the methods that come with an object by default. It’s in my .irbrc file so I can append this method at any time when I am working in IRB.

Other than that, it’s a handy little concept to remember even if you’re debugging. Just doing the following can help you deal with those pesky NoMethod errors on objects:

p (MyObject.methods - Object.new.methods).sort
Posted in Ruby. Tags: , . 1 Comment »
  • http://rapexegesis.com Anonymous

    Object.instance_methods is a more readable way of saying Object.new.methods