Get list of a class' instance methods

Vladimir Tsukanov picture Vladimir Tsukanov · Jun 24, 2011 · Viewed 102.2k times · Source

I have a class:

class TestClass
  def method1
  end

  def method2
  end

  def method3
  end
end

How can I get a list of my methods in this class (method1, method2, method3)?

Answer

Andrew Grimm picture Andrew Grimm · Jun 24, 2011

You actually want TestClass.instance_methods, unless you're interested in what TestClass itself can do.

class TestClass
  def method1
  end

  def method2
  end

  def method3
  end
end

TestClass.methods.grep(/method1/) # => []
TestClass.instance_methods.grep(/method1/) # => ["method1"]
TestClass.methods.grep(/new/) # => ["new"]

Or you can call methods (not instance_methods) on the object:

test_object = TestClass.new
test_object.methods.grep(/method1/) # => ["method1"]