On Feb 2, 2006, at 11:08 AM, James H. wrote:
(i)
Class.superclass
=> Module
Class.ancestors
=> [Class, Module, Object, Kernel]
Do I understand the Class.ancestors relationship to mean “those
classes which are implemented by the Class class”? (I had to remind
myself that Ruby isn’t really single inheritance – it has mixins
and whatnot)
No. X.ancestors returns the list of modules that will be searched
when a method is called on an instance of X. I say modules to
include both direct instances of Module and indirect instances of
Module via Class (i.e., Class is a subclass of Module
so instances of Class are also indirectly instances of Module).
The ancestors array is constructed from the strict subclass
relationship and dynamically modified by the include method
to implement the mixin of modules. Instead of starting with the
self-referential confusion of Class, lets start with some user-
defined classes:
class A; end
A.ancestors => [A, Object, Kernel]
class A
include Comparable
end
A.ancestors => [A, Comparable, Object, Kernel]
class B < A; end
B.ancestors => [B, C, Comparable, Object, Kernel]
Let’s look at String now:
String.ancestors => [String, Enumerable, Comparable, Object, Kernel]
s = String.new # create new instance of String
s.object_id # Ruby will search for the method ‘object_id’ in
# String, Enumerable, Comparable, Object, and Kernel
# In this case it will find the method in Kernel.
s.size # This time the method is found right away in String
Now lets consider Class. Class is a strange beast since it is an
instance of
itself and also the origin class of all other classes.
String.class # Class
Object.class # Class
Class.class # Class (instance of itself!)
Class.ancestors => [Class, Module, Object, Kernel]
Since Class is an instance of itself, an attempt to call
Class.x
will search for a definition of x in Class, Module, Object, and Kernel.
For example
Class.superclass # Module
will be found in Class itself. Now consider
String.superclass # Object
In this case String is an instance of Class (String.class is Class)
so Ruby searches for the superclass method in the modules listed in
Class.ancestors.
Gary W.