Ruby is magical in its abilities to extend an already existing object and a class etc. How does it do?
First, realize that in Ruby, everything is an object. An object basically has space for the object-scope variables (similar to private variables in Java and C++). However, object has no space for methods.
Then where are these methods stored?
The object method are stored in another object typically the Class object of the current object. Object in addition to space for object-scope variable also have a pointer to the Class object using which the methods are accessed.
Class inheritance then is implemented as pointers to classes all the way up the inheritance chain.
So how do you add a method to just one object?
Obviously the method can not be added to the Class since that would affect every object of that class.
In this case, Ruby using a special syntax to create bubble-wrap object behind the curtains to wrap the current object. A method added to this bubble-wrap object (of type Class) is only usable to the object it surrounds.
Let’s say,
dude= "Sudheer" def dude.greet() "Hello " + self + "!" end dude.greet --> Hello Sudheer!
Now, the string “dude” has a method added called “greet”. However, this method is not added to the String class. A new bubble-wrap class is created with the ‘greet’ method is attached in that wrap!
For curious, the inheritance chain is preserved by the bubble-wrap class having its class pointed to the object ‘dude’s class!
October 29, 2007 at 4:00 am
[...] class method are stored in the bubblewrap class (aka metaclass) that surrounds the class object. Viola, the problem is solved by not [...]