Quantcast
Channel: Ruby – Live. Interesting. Stories
Viewing all articles
Browse latest Browse all 10

Interesting Object Methods in Ruby

$
0
0

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:

1
2
3
4
5
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:

1
p (MyObject.methods - Object.new.methods).sort

The post Interesting Object Methods in Ruby appeared first on Live. Interesting. Stories.


Viewing all articles
Browse latest Browse all 10

Trending Articles