"Object is the root of Ruby's class hierarchy. Its methods are
available to all classes unless explicitly overridden."

Wouldn't Class class be at the root of the class hierarchy?


After all, look at this:

1.9.2p290 :006 > Object.instance_of? Class
 => true

Object is an instance of class, after all we can use one of Class'
instance methods on Object:

1.9.2p290 :017 > Object.new
 => #<Object:0x007faad047ecd0>



But Class is not instance of Object:

1.9.2p290 :007 > Class.instance_of? Object
 => false
1.9.2p290 :008 > defined? Class
 => "constant"
1.9.2p290 :009 > Class.class
 => Class
1.9.2p290 :010 > Object.class
 => Class

Class is an instance of Class. That is, Class is an instance of
itself. And therefore "Class" just is (kind of like the idea if
something stems from something else, how was the very first thing
created - it just was). Class is just an internal construct, built
part of the language for templating.

So Object is a constant that represents an object allocated in memory.
When it's methods are searched for it looks up the scope chain, first
at the singleton class (just in case any methods are extended on
Object) and after that, it looks at its immediate parent which is
Class, and hence that's why we can say Object.new, since Class class
defines "new".

Now this is the interesting part. There obviously is a difference
between Object and Class. As already stated, Object is an instance of
Class and therefore inherits from Clas, not visa versa.

The difference is made clear as shown below:

We have a constant "A". We want that constant to be a class, so we do
it easily:

A = Class.new

We know that A is a class because we can run A.new.

However, when we create an object:

B = Object.new

This fails:
1.9.2p290 :007 > B.new
NoMethodError: undefined method `new' for #<Object:0x007ff597d27820>


When we instantiate B, the instance gets B's instance methods. But why
doesn't it get Class's instance method (new)?

B inherits from Object which inherits from Class. It should have
looked up scope chain until it reached Class, since Object is an
instance of Class and therefore inherits from it.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to