Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of instance methods of current class only

Tags:

ruby

I have an instance o of class O. I'd like to know what o is capable of.

o.methods will give me many methods. So I usually do o.methods - Object.instance_methods. But that is not concise.

I want to do something like o.methods - o.class.superclass.instance_methods. That is, just the methods defined in O itself.

Is there some other way?

like image 331
Michiel de Mare Avatar asked Jul 25 '13 13:07

Michiel de Mare


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 .

What are instance and class methods?

Instance method performs a set of actions on the data/value provided by the instance variables. If we use instance variables inside a method, such methods are called instance methods. Class method is method that is called on the class itself, not on a specific object instance.


1 Answers

You can use the method Module#instance_methods:

o.class.instance_methods(false)


Warning The documentation seems to be wrong, it says that:

With no argument, or with an argument that is false, the instance methods in mod are returned, otherwise the methods in mod and mod’s superclasses are returned.

But actually the parameter by default is true:

String.instance_methods.size
# => 184
String.instance_methods(false).size
# => 130
like image 109
toro2k Avatar answered Oct 13 '22 20:10

toro2k