On Thu, 29 Mar 2007 04:44:16 +0900, "John Lam (CLR)" <jflam / microsoft.com> wrote:
> I was wondering if someone could help me understand why there's a parallel
> class hierarchy - there's the 'real' class objects which holds onto
> instance methods, and the 'virtual' class object that holds onto class
> methods.

Every (non-value-typed) object in Ruby has an accompanying "virtual" class, permitting "one-off" ("singleton") methods to be attached to it.  As calls to "class methods" are simply regular method calls that happen to have a class as the receiver, it was probably simplest not to make classes a special case in this regard.

These virtual classes are in fact visible to Ruby code, are most commonly referred to as "singleton classes" or (more descriptively) "eigenclasses", and can be extracted via a construct like:

 class Object
   def eigenclass
     class << self
       self
     end
   end
 end

(one would then call obj.eigenclass to get obj's eigenclass)

There is one slight difference in method lookup between class objects and other objects, though.  While for most objects, the search order could be obtained via:

 class Object
   def method_search_order
     [ self.eigenclass ] + self.class.ancestors
   end
 end

...classes also include their ancestor classes' "eigenclasses" in the search:

 class Class
   def method_search_order
     ancestors.select { |m| Class === m }.map { |c| c.eigenclass } + self.class.ancestors
   end
 end

-mental