Assignments

F

Ftf 3k3

Hello folks, I have a question about Ruby 1.8.7.

After doing:

a = b = 1
a += 1

a returns 2 and b returns 1.

But if I try:

a = b = []
a << 1

both a and b returns [1]. Why?

Regards
 
G

Gregory Brown

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
 
P

Pascal J. Bourguignon

Ftf 3k3 said:
Hello folks, I have a question about Ruby 1.8.7.

After doing:

a = b = 1
a += 1

a returns 2 and b returns 1.

But if I try:

a = b = []
a << 1

both a and b returns [1]. Why?

Because a<<1 doesn't modify a. It sends the message << with the
argument 1 to the object referenced by a. But it's always the same
object that's referenced by a, and of course, it's the same that is
referenced by b too.

In the case of a+=1, you are misled by the syntax (too much syntax
gives the cancer of the semicolon). a+=1 is actually a = a+1, which
is sending the message + with the argument 1 to the obejct referenced
by a. That object will behave according to its method, and will
return a new object. This new object will now be referenced by a.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,045
Latest member
DRCM

Latest Threads

Top