Some ruby introspection

Published October 10, 2008 in Ruby

Ever tried to remember the name of the method that gives you a particular value? Thanks to the ease of introspection with Ruby, you can ask an object which of its methods returns the value you expect.

class Object
  def find_method(expected_output, *args)
    (self.methods - Object.methods).sort.select  do |method|
      begin
        self.clone.send(method.to_sym, *args) === (expected_output)
      rescue
        next
      end
    end
  end
end

%w(a b c d e).find_method("a") # => ["first", "min", "shift"]
"a".find_method(:a)            # => ["intern", "to_sym"]

I’ve been meaning to get that out there for a while, since it’s been a handy tool in my toolbox when my memory fails.