Search code examples
rubyreflectionruby-1.9.2

Get list of a class' instance methods


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)?


Solution

  • 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"]