Ruby uses message passing to invoke specific behaviours. When a Ruby object receives a message, it checks to see if a method of the same name exists. If there is one, that method is invoked with the appropriate parameters. If the method doesn't exist, it calls the
method_missing method and passes the message to it. We cover
method_missing in the RubyMonk Metaprogramming: Method missing lesson.
How does Ruby know whether a method 'exists' in an object or not? Take a look at these method invocations:
object_id, class were not defined by the class Foo. It is however present in every object created from Foo. In fact, these methods are present in every object in the Ruby object space. How is this possible? Where do these methods magically appear from? We will answer these questions and understand Ruby's object model better in the course of this chapter.
The first thing to note is that every object in Ruby by default inherits from the class
Object. The two snippets of code below are identical:
class Foo end class Foo < Object end
class Foo < Object means that
Foo inherits behaviour from
Object. In practice, that means that every instance instantiated by
Foo will include all the instance methods defined by
Object. Since by default every Ruby object inherits from Object, all instance methods defined by
Object are available to every object in Ruby. The methods
class are thus available everywhere.
Here is an interesting fact: even the class definition object
Foo is an object and hence begets the behaviour exposed by the
Object class. We can use the
is_a? method to check whether this is true.
is_a? method tells you whether the object contains behaviour of the given class. As you can see, both the class definition object
Foo and an instance created from Foo share