Friday, August 24, 2012

A quick review of singleton class(eigenclass) and class methods

First think about an object(o1)'s singleton methods.
For a method used just by this object(o1), you can't define a method in its class, since this will make this method available to all instances of the object's class. (An Class object in Ruby actually only have instance methods like:

class C1
def met1
# ...
end
end

Class method is more like an abstraction concept)

So we add an anonymous object (anon) between the object and its class, since this anon object only exists as a new class of the object and subclass of the object's original class, all its instance methods can be only called by the object, so this anon object is the singleton class(eigenclass) of the object o1, and its instance methods are singleton methods for the object o1.

Second,
If the object o1 represents a class (for example, o1's class is class Class), it can have its own methods, but these are instance methods that will be used by all its instances, not by herself.

Based on the above explanations, we'll have a singleton class for this o1 if we considering this class object as an object (a lit confusing, but don't forget everything in Ruby is an object). The instance methods in this singleton class can only be called by the class object o1 and they're actually the class methods we saw in:

class C1
def self.met2
#...
end
end 

To help understand, I borrow the pics from the classical the Pickaxe Book: Programming Ruby 1.9. The big arrow indicates the addition of single method to the class object Dave (equivalent to class object o1 above)


No comments:

Post a Comment