Ruby Object Model : The Method Lookup in Ruby

Objective


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

Steps


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'
  end  
end

Step 2

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

class Greeter

end

g = Greeter.new
g.greet

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'
  end
end

class Greeter

end

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
  end

  def welcome
    @text
  end
end

o = Greeting.new('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]

Summary


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