Assignments

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

On Thu, Jul 30, 2009 at 9:25 AM, Ftf 3k3[email protected] 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:

a = b = 1
a += 1

This translates to a = 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 +=

a returns 2 and b returns 1.

But if I try:

a = b = []
a << 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 += [1]

which translates to

a = 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 = b = some_obj

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

-greg

Gregory B. wrote:

Hope this helps.

-greg

Thanks that’s very helpful!

Ftf 3k3 [email protected] writes:

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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs