In the book The Well Grounded Rubyist (excerpt), David Black talks about the "Class/Object Chicken-and-Egg Paradox". I'm having a tough time understanding the entire concept.
Can someone explain it in better/easier/analogical/other terms?
Quote (emphasis mine):
The class
Class
is an instance of itself; that is, it’s aClass
object. And there’s more. Remember the classObject
? Well,Object
is a class... but classes are objects. So,Object
is an object. AndClass
is a class. AndObject
is a class, andClass
is an object.Which came first? How can the class
Class
be created unless the classObject
already exists? But how can there be a classObject
(or any other class) until there’s a classClass
of which there can be instances?The best way to deal with this paradox, at least for now, is to ignore it. Ruby has to do some of this chicken-or-egg stuff in order to get the class and object system up and running—and then, the circularity and paradoxes don’t matter. In the course of programming, you just need to know that classes are objects, instances of the class called
Class
.(If you want to know in brief how it works, it’s like this: every object has an internal record of what class it’s an instance of, and the internal record inside the object
Class
points back toClass
.)
You can see the problem in this diagram:
(source: phrogz.net)
All object instances inherit from Object
. All classes are objects, and Class
is a class, therefore Class
is an object. However, object instances inherit from their class, and Object
is an instance of the Class
class, therefore Object
itself gets methods from Class
.
As you can see in the diagram, however, there isn't a circular lookup loop, because there are two different inheritance 'parts' to every class: the instance methods and the 'class' methods. In the end, the lookup path is sane.
N.B.: This diagram reflects Ruby 1.8, and thus does not include the core BasicObject
class introduced in Ruby 1.9.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With