Ruby Object Model : The Method Lookup in Ruby


To learn about the introspection abilities of Ruby and method lookup.


Step 1

We already know that class Object is the super class of any user defined class. Let's define a greet method by opening the Ruby's built-in Object class.

class Object
  def greet
    puts 'hi'

Step 2

Let's create a class and call the method greet on it.

class Greeter


g =

This prints : 'hi'. The method looks for the method greet in the Greeter class, it does not find it there. So it goes to the superclass of Greeter which is the Object, since it is defined there, it calls the method.

Step 3

We can ask ruby for its method look up path like this:

class Object
  def greet
    p 'hi'

class Greeter


p Greeter.ancestors

This prints : [Greeter, Object, Kernel, BasicObject]. This shows that Ruby looks for the method in the Greeter class, then Object, then Kernel module and finally the BasicObject.

Step 4

Let's look at a simple example that we can use to experiment and learn.

class Greeting
  def initialize(text)
    @text = text

  def welcome

o ='Hi')
p o.class

This prints : 'Greeting'. We know the instance of Greeting, the object o is created using the Greeting class. We can also get the instance methods, instance variables as follows:

p o.class.instance_methods(false)

This prints : [:welcome]

p o.instance_variables

This prints : [:@text]


In this article, we saw the introspection abilities of Ruby by asking for its instance variables, instance methods, ancestors. Why do we need to worry about class hierarchy in Ruby? Because it determines the method lookup in Ruby.

Related Articles

Create your own user feedback survey