Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I inspect the methods of a Ruby object?

Tags:

I am wondering if there is a Ruby method call that shows only the methods defined by the Ruby object it's called from, as opposed to all the methods defined by its ancestor classes, which is what methods seems to do.

like image 865
picardo Avatar asked Jan 12 '11 01:01

picardo


People also ask

What is inspect method in Ruby?

inspect is a String class method in Ruby which is used to return a printable version of the given string, surrounded by quote marks, with special characters escaped. Syntax: str.inspect. Parameters: Returns: Here, str is the given string.

How does Ruby search for methods?

If the class has a parent class, Ruby searches in the class. The search includes going into the modules mixed into the parent class; if we had the method defined in a module mixed into the Creature class, the method will get called.

Are methods in Ruby objects?

In Ruby, methods are not objects.

How do you access a class method in Ruby?

Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.


2 Answers

methods takes an optional boolean parameter, which specifies whether to also list the methods from the object's class and its superclasses or just the object's singleton methods. So you can do obj.methods(false) to only get the singleton methods defined on obj.

If you want the methods defined by the object's class, but not those defined by its superclasses, you can get that by calling instance_methods(false) on the object's class, so it's obj.class.instance_methods(false).

like image 78
sepp2k Avatar answered Oct 13 '22 03:10

sepp2k


I'm partial to obj.methods.sort but some of the other answers are better in certain cases as they describe

You can also use obj.methods.sort.grep /foo/ to find method names matching the regexp. This is helpful when you have an idea of what you're looking for.

like image 25
EnabrenTane Avatar answered Oct 13 '22 04:10

EnabrenTane