Hi, I don’t understand some Ruby logic. As we know every object in Ruby
inherit Object class. And every class is instance of Class which inherit
Object. But how it possible that Object.class is Class and at the same
time Class inherit Object? Which class creates earlier Object or Class?
If Object that mean that firstly it’s not Class object, but later after
Class inherit it, it’s become Class object. If Class first it’s mean
that for some time it don’t inherit Object.
They’re part of the language core, so it’s a special case where they are
both related to each other.
Forget about that; what about this:
1.9.3-p547 :001 > Class.class
=> Class
Which comes first: Class or Class? Ha!
You should think that Ruby was created in C++, there exist multiple
inheritance and Matz and his friend had handled something to make this
behaviour, which is excellent. Check this out also:
Something = Class.new
then you can open it to define things
Something.class_eval do
#do stuff
end
There is a sheer logic behind and Ruby is consistent here
Every object in Ruby has its place in inheritance hierarchy. Each
inheritance hierarchy has its own top ancestor, common to all
descendants.
Classes are also objects because they are first-class citizens in Ruby
and it allows them to be created and manipulated dynamically during a
runtime.
Top ancestor of all classes is named `(Basic)Object’.
Any object is an instance of a specific class.
To satisfy former conditions classes(as objects) also need to be
instances of some class ! This class of classes is named `Class’, also
called metaclass.
But what about metaclass Class ?
To keep above logic the same rules need to apply, so
- class Class is also an object so it also derives from `(Basic)Object’
- class Class as all classes is an instance of metaclass Class so it’s
an instance of itself !
This strict logic leads to above described cyclic dependency and
relationship which is handled in core of the language and cann’t be
altered.
p.s. There is a wired-in system of singleton classes for each class and
modules but didn’t intend to complicate explanation as the same rules
apply anyway.