Ruby Object Model : The Method Lookup in Ruby
To learn about the introspection abilities of Ruby and method lookup.
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
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.
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.
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:
This prints : [:welcome]
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.