I m trying to understand the Ruby Object Model. I understood that the instance methods are saved in the class rather than in the objects of the class because it removes redundan
This isn't quite an answer to your question, but it might be useful. Two things to think about that might help:
The eigenclass is used to store methods that are specific to a particular object. e.g. we can add a method to a single String object:
my_string = 'Example'
def my_string.example_method
puts "Just an example"
end
This method can only be called on my_string
and not on any other String object. We can see that it is stored in my_string
's eigenclass:
eigenclass = class << my_string; self; end # get hold of my_string's eigenclass
eigenclass.instance_methods(false) # => [:example_method]
Remembering that classes are objects, in this context, it makes sense that the methods specific to a particular class should be stored in that class's eigenclass.
Update: actually, there is an eigenclass for the eigenclass. We can see this more easily if we add eigenclass
as a method to Object:
class Object
def eigenclass
class << self
self
end
end
end
and then we can do:
irb(main):049:0> my_string.eigenclass
=> #>
irb(main):050:0> my_string.eigenclass.eigenclass
=> #>>
irb(main):051:0> my_string.eigenclass.eigenclass.eigenclass # etc!
=> #>>>
whilst this seemingly creates an infinite regress, this is avoided because Ruby only creates the eigenclasses on as they are needed. I think the name "metaclass" really is a source of part your confusion because you are expecting a "metaclass" to hold some kind of information that it actually doesn't.