Ruby - determining method origins?

To find which instance methods are defined on A (but not on superclasses):

A.instance_methods(false)

To find which instance methods are defined on A AND its superclasses:

A.instance_methods

To find which class (or module) a given method is defined on:

method(:my_method).owner

To find which object is the receiver for a given method:

method(:my_method).receiver

You can use Object#method. For example,

[1, 2, 3].method(:each_cons) # => #<Method: Array(Enumerable)#each_cons>

tells that the each_cons method of an Array comes from the Enumerable module.


Get the appropriate Method (or UnboundMethod) object and ask for its owner. So you could do method(:puts).owner and get Kernel.


Object#method returns a Method object giving meta-data about a given method. For example:

> [].method(:length).inspect
=> "#<Method: Array#length>"
> [].method(:max).inspect
=> "#<Method: Array(Enumerable)#max>"

In Ruby 1.8.7 and later, you can use Method#owner to determine the class or module that defined the method.

To get a list of all the methods with the name of the class or module where they are defined you could do something like the following:

obj.methods.collect {|m| "#{m} defined by #{obj.method(m).owner}"}

Tags:

Ruby