On Thu, Jul 30, 2009 at 9:25 AM, Ftf 3k3<ftf3k3 / gmail.com> wrote:
> Hello folks, I have a question about Ruby 1.8.7.

This question actually applies to all Ruby versions.

It's important to remember that variables in Ruby are just labels for
references.   From that, here are some hints:

> After doing:
>
> =A0a =3D b =3D 1
> =A0a +=3D 1

This translates to a =3D a + 1
Because Fixnums are immediate values in Ruby, Fixnum#+ does not modify
the original object, it instead returns a new one.

So even though a and b originally pointed to the same object, you are
reassigning a to a new object when you do +=3D

> a returns 2 and b returns 1.
>
> But if I try:
>
> =A0a =3D b =3D []
> =A0a << 1
>
> both a and b returns [1]. Why?

a and b are pointing to the same object.  Array#<< is a destructive
operator, and modifies the object itself.  Since you do not re-assign
a, it still points at the original object, as does b.

If you wanted to do this in a nondestructive way, you could do:

a +=3D [1]

which translates to

a =3D a + [1]

which would create a new array and reassign a to it.

But generally speaking, except for with simple values like numbers,
boolean states, and things of that like, you don't want to do:

a =3D b =3D some_obj

unless you intentionally want two labels point to that single object.
Hope this helps.

-greg