Classes are objects, objects are Classes

Consider this irb section:

irb(main):003:0> class Bla; end
=> nil
irb(main):004:0> b = Bla.new
=> #
irb(main):005:0> b.class
=> Bla
irb(main):006:0> b.new
NoMethodError: undefined method `new' for #
irb(main):007:0> c = Class.new
=> #
irb(main):008:0> c.new
=> #<#:0x2b5f570>
irb(main):009:0> c.class
=> Class

So, an interesting thing happened here. The variable ‘c’ is an instance of a class Class and you can create another instance of ‘c’ by calling ‘c.new’ however ‘b’ instance of class Bla tells us ‘undefined method’ when we try to do b.new.

Consider this from Ruby for Rails book:

Classes are objects; specifically, they are instances of the class Class (…) When you instantiate the class Class—when you create an instance of it—you’ve created a class. That class, in turn, can create instances of its own (…) class objects are usually stored in constants (…) in the previous example, however, we’ve stored a class in a regular variable When we call the .new method, we send the message new to the class through that variable

And yes, there is a paradox here. 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—at which point the circularity and paradoxes don’t matter. In the course of programming, you just need to know that classes are objects, and the class of which class-objects are instances is the class called Class.

close Reblog this comment
blog comments powered by Disqus