On Sun, Feb 7, 2010 at 9:13 PM, Ruby N. [email protected]
wrote:
Hello,
Please see the code about, why Myclass.superclass is “Object”? But I
think it should be “Module”.
Thanks for your helps.
class MyClass
end
MyClass.class # => Class
MyClass.superclass # => Object
MyClass.ancestors # => [MyClass, Object, Kernel]
Class.class # => Class
Class.superclass # => Module
Class.ancestors # => [Class, Module, Object, Kernel]
From here, I see that MyClass’s class and superclass are congruent with
it’s
ancestors, and so are Class’s. However, I am also a bit confused, it
seems
that if MyClass inherits from Class, then it should include Module in
it’s
ancestors. I thought about it a bit, and decided to check if included
modules of Class are visible to MyClass
module DoYouSeeMe
end
class Class
include DoYouSeeMe
end
MyClass.class # => Class
MyClass.superclass # => Object
MyClass.ancestors # => [MyClass, Object, Kernel]
Class.class # => Class
Class.superclass # => Module
Class.ancestors # => [Class, DoYouSeeMe, Module, Object, Kernel]
So apparently not. I decided to generalize this into a hypothesis that
included modules are not visible to subclasses.
class MyClass
include DoYouSeeMe
end
class MyInheritedClass < MyClass
end
MyClass.class # => Class
MyClass.superclass # => Object
MyClass.ancestors # => [MyClass, DoYouSeeMe, Object,
Kernel]
MyInheritedClass.class # => Class
MyInheritedClass.superclass # => MyClass
MyInheritedClass.ancestors # => [MyInheritedClass, MyClass,
DoYouSeeMe,
Object, Kernel]
class MyClass
include DoYouSeeMe
end
class MySubClass < MyClass
end
MyClass.class # => Class
MyClass.superclass # => Object
MyClass.ancestors # => [MyClass, DoYouSeeMe, Object,
Kernel]
MySubClass.class # => Class
MySubClass.superclass # => MyClass
MySubClass.ancestors # => [MySubClass, MyClass, DoYouSeeMe,
Object, Kernel]
Apparently I was wrong. I thought about it a little bit more, and
decided
that maybe MyClass didn’t inherit from Class, but was rather an instance
of
class
MyClass.instance_of? Class # => true
MySubClass.instance_of? MyClass # => false
MyOtherClass = Class.new
MyOtherClass.ancestors # => [MyOtherClass, Object, Kernel]
This seems to be congruent
So, my conclusion is that class and superclass behave correctly, in that
they reflect their ancestry. And the reason MyClass’ ancestry is not a
superset of Class’ ancestry is because MyClass is not a subclass of
Class,
but rather an instance of it. ( I tried making a subclass of Class also,
but
got a TypeError )
Hope that helps, thanks for asking, it was a useful exercise