Method Lookup in irb

If you follow _why’s instructions for irb tab completion, you’ll have a great solution for looking up methods if you can remember what the method starts with. However, many times you will need a more flexible lookup mechanism without leaving your irb session. This is a recap of a prior post on the subject which allows you to search multiple keywords at once.

To set one up, open up a ~/.irbrc file and add these lines:


class Object
  def ml(*m)
    result = []
    m.each do |t|
      result << methods.grep(/#{t}/)
    end
    result.flatten.uniq!
  end
end

Then pop open a new irb session to try it out:


$ irb
irb(main):001:0> [].each (TAB-->)
[].each             [].each_index       [].each_with_index  

irb(main):002:0> [].with  (TAB-->)
NoMethodError: undefined method `with' for []:Array
	from (irb):1

irb(main):003:0> [].ml :with
=> ["each_with_index"]

irb(main):004:0> [].ml :each
=> ["each_index", "reverse_each", "each_with_index", "each"]

irb(main):005:0> [].ml :each, :with
=> ["each_with_index", "each_index", "reverse_each",
       "each"]

This can be called on any object, including Object itself.

UPDATE: Tweaked the code slightly so duplicates are actually removed. Removed the use of ’set’.

3 comments ↓

#1 Peek Inside Your Database From Rails Console » Damon Clinkscales on 03.06.08 at 1:22 pm

[…] our last posting, we looked at how to add a simple method lookup to irb. Another cool trick to have in your bag while consoling is to use an irb subsession to […]

#2 Mars on 03.19.08 at 1:40 am

Heed caution when adding code to ~/.irbrc. It may be forgotten, and years down the road unfortunately vague Rubygems exceptions may plague Rails console, preventing interactive boot-up, causing hours of lost labor for the corpratocracy.

#3 damon on 03.19.08 at 7:49 am

hehe, tis true.

Leave a Comment