Strange Symphonies Don’t worry, be happy

19Oct/080

Sort Listings of an Object’s Methods in IRB

I constantly use IRB to debug and test code. I don't only use it for testing, but also for finding "that method" that I know exists, just I had forgotten its name. Or even looking for what methods are available to a given object.

Luckily for me there is a convenient Object#methods which returns to me an array with all the method names. So likewise I would pull up a console and call:

object.methods

Where object is the name of the variable I would like to examine to find out its methods.

The Problem

But it's not nice. The method names don't come out sorted.

Since the result is an array, you end up doing this to sort it:

object.methods.sort

Much better in my opinion, alphabetical order makes things so much easier to find. But still a bit tedious. Plus I sometimes forget to append the #sort method call.

The Solution

So what is a Ruby programmer to do? Well thanks to Open Classes we can modify the method calls directly.

Stuff this gem into your ~/.irbrc:

class Object
  def methods_with_sort
    methods_without_sort.sort
  end
  alias_method :methods_without_sort, :methods
  alias_method :methods, :methods_with_sort
end

And try it:

object.methods

Beautiful.

What else can we do this with? Oh why not the #instance_variables?

class Object
  def instance_variables_with_sort
    instance_variables_without_sort.sort
  end
  alias_method :instance_variables_without_sort, :instance_variables
  alias_method :instance_variables, :instance_variables_with_sort
end

And try it:

object.instance_variables

Now, how cool is that?

For those curious folk, this is the same magic that #alias_method_chain does in Rails.

Related posts

Tags

Tagged as: , Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.