Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 980
Vladimir Tsukanov Avatar asked Jun 24 '11 13:06

Vladimir Tsukanov


People also ask

How do you get all methods in a class?

Method 1 – Using the dir() function to list methods in a class. To list the methods for this class, one approach is to use the dir() function in Python. The dir() function will return all functions and properties of the class. Let's see what happens if we try it for MyClass .

How do you print a class method in Python?

Print an Object in Python Using the __str__() Method Now, let's define the __str__() method of our example class ClassA and then try to print the object of the classA using the print() function. The print() function should return the output of the __str__() method.

Does Ruby have class methods?

There are two standard approaches for defining class method in Ruby. The first one is the “def self. method” (let's call it Style #1), and the second one is the “class << self” (let's call it Style #2). Both of them have pros and cons.


1 Answers

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"] 
like image 177
Andrew Grimm Avatar answered Oct 13 '22 21:10

Andrew Grimm