Matt T. wrote:
So, what is an eigenclass? I googled it, and couldn’t find anything
about it (other than Mauricio’s great blog/wiki). Wikipedia doesn’t
have anything on it other than an indirect relation to Metaprogramming
(which I already know it’s a part of, just not sure wherein).
Can someone provide some information on the idea of an eigenclass?
I’ll try. (I call it “singleton class” since that is what I learned.)
It’s the “place” where things go that are associated with a specific
object rather than a class of objects.
For example, if I add a method to an object, that method “lives” in
the singleton class.
superman = “Clark Kent”
def superman.fly
puts “Look! I’m flying!”
end
Here the “fly” method is certainly not part of the String class. No
other string responds to that method – only this one. It’s a
singleton method, and it “lives” in the “singleton class.”
You can see more clearly the class-like nature of this thing if
we use this syntax:
class << superman
def fly
#…
end
end
That at least “looks” like a class. But also be aware:
- It’s not a “real” class in that it can’t be instantiated.
- Matz has said that this “thing” may not be considered a
class in the future (IIRC).
Note that we can capture the actual value of the singleton class
if we want to:
ssc = class << superman # ssc = superman’s singleton class
self # return self as last expression
end
puts ssc.class # Class
Finally, note that what we call “class methods” are just a special
case of singleton methods. Suppose Dog inherits from Mammal; then
suppose we make a Dog.bark class method.
Where does “bark” live? Clearly not “in” Dog (as an instance method
would be “in” it). Not in the parent class, either. It lives in the
singleton class of Dog.
So a “class method” is really just “a singleton method on an object
which happens to be a class.”
Does that help any?
Hal