Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Class/Object Paradox confusion

Tags:

ruby

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 a Class object. And there’s more. Remember the class Object? Well, Object is a class... but classes are objects. So, Object is an object. And Class is a class. And Object is a class, and Class is an object.

Which came first? How can the class Class be created unless the class Object already exists? But how can there be a class Object (or any other class) until there’s a class Class 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 to Class.)

like image 281
Zabba Avatar asked Oct 06 '11 14:10

Zabba


1 Answers

You can see the problem in this diagram:

Ruby Method Lookup Flow
(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.

like image 148
Phrogz Avatar answered Sep 20 '22 15:09

Phrogz