How do I inspect the methods of a Ruby object?

14,003

Solution 1

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

Solution 2

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.

Solution 3

You have a few options - object.methods, object.public_methods, object.singleton_methods... it depends on what you want. Since they both return an array, you might want to try something like:

# obj is the current object
parent = obj.class.superclass

methods = (obj.methods - parent.methods)
Share:
14,003

Related videos on Youtube

jdahlgren
Author by

jdahlgren

Updated on April 05, 2020

Comments

  • jdahlgren
    jdahlgren about 4 years

    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.

  • cHao
    cHao over 13 years
    whatever.methods returns an Array in the version of Ruby i'm running. Same with whatever.public_methods.