On Apr 6, 2007, at 9:24 AM, Jamal Soueidan wrote:
> When does the instance variable holds the object itself?

Instance variables never hold the objects themselves.
Ruby variables always hold references to objects.

Note: It is often explained that in some special cases
Ruby variables hold 'immediate values'.  Such as small
integers as Fixnum instances and the unique objects
nil, false, and true.  I think that this is an
unnecessary complication.  It is easier and more
consistent to always talk about references.  In
particular assignment is always about copying a
reference and *never* about duplicating an object
or a value:

a = 1       # 1 is a reference to a Fixnum
             # now a references the same fixnum
b = a       # b now references the same fixnum as a

a = "foo"   # a is a reference to a string instance
b = a       # b now references the same string as a

The 'trick' is to think of literals (-1,0,1,nil,true,false, etc.)
as references and *not* as values or objects.

I'd almost go as far to say that in Ruby there is only
one type of value, an object reference.  Assignment, method
argument passing and return values are all about the copying
of references and not at all about objects.


> class A; end;
>
> @one = A.new
> @two = A.new
>
> p @one.object_id
> p @one_object_id
> # 21103660
> # 21103640
>
> Two different objects, even if they were the same.

Do you have a typo there?  Do you want:

   p @one.object_id
   p @two.object_id

These are two different objects and so they have two
different object ids.  I'm not sure what your question
is here.

> How does all the nil instance variable reference to the same object?

Can you rephrase the question?  I'm not sure what you are asking.

@a = nil
@b = @a
@c = @b

All three instance variables now reference the same object.  It
is the same object referenced by the literal, nil.  Don't think
of 'nil' as an object.  Think of it as a reference to a particular
distinguished object.