No Class in ancestors

Hello.

I’m learning metaprogramming and have some questions .

I create new class this way:

ClassNew = Class.new

But puts ClassNew.ancestors returns:
=> [ClassNew, Object, Kernel, BasicObject]

without Class .

The same situation for Module:
ModuleNew = Module.new
puts ModuleNew = Module.new # => [ModuleNew] (no Module inside!)

But for example for Struct everything fine:
ClassNewest = Struct.new(:x, :y)
puts ClassNewest.ancestors # => [ClassNewest, Struct, Enumerable,
Object, Kernel, BasicObject]

Why? Class Module and class Class are so special?

create a new instance of Class

ClassNew = Class.new

ClassNew is a Class

puts ClassNew.class

Class is not the superclass of ClassNew

class ClassNew < Class
end
TypeError: can’t make subclass of Class
from (irb):1
from C:/ruby2.2.1-p85/bin/irb:11:in `’

Does that help?

Scott S. wrote in post #1170148:

create a new instance of Class

ClassNew = Class.new

ClassNew is a Class

puts ClassNew.class

Class is not the superclass of ClassNew

class ClassNew < Class
end
TypeError: can’t make subclass of Class
from (irb):1
from C:/ruby2.2.1-p85/bin/irb:11:in `’

Does that help?

Yes. More clear now.

ClassNew is instance of Class.
But class Class (and Module) is special and cannot have subclasses.

Arthur G. wrote in post #1170151:

ClassNew is instance of Class.
But class Class (and Module) is special and cannot have subclasses.

That’s not quite right because Class is a subclass of Module. Also,
you can do this:

class Dog < Module
end

p Dog.ancestors

–output:–
[Dog, Module, Object, Kernel, BasicObject]

So, Class is the special one.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs