Beware ruby's var1 = var2 = "value" multiple assignment

Posted . Visible to the public.

This looks like it is safe to use:

2.2.1 :001 > a = b = "hello world"
"hello world"
2.2.1 :002 > a
"hello world"
2.2.1 :003 > b
"hello world"
2.2.1 :004 > b = " goodbye!"
" goodbye!"
2.2.1 :005 > a
"hello world"
2.2.1 :006 > b
" goodbye!"

But it isn't!

2.2.1 :010 > a = b = "hello world"
"hello world"
2.2.1 :011 > a
"hello world"
2.2.1 :012 > b
"hello world"
2.2.1 :013 > b << " goodbye!"
"hello world goodbye!"
2.2.1 :014 > a
"hello world goodbye!"
2.2.1 :015 > b
"hello world goodbye!"

What is happening when we do a = b = "hello world"?
First, b is assigned to a String object "hello world", then a is assigned to b. a and b are now assigned to the same object:

2.2.1 :018 > a.object_id
21462560
2.2.1 :019 > b.object_id
21462560

With e.g. << this object is manipulated, so the value is changed for all variables pointing to it.
Whereas with = a new object is assigned to a variable:

2.2.1 :020 > a = b = "hello world"
"hello world"
2.2.1 :021 > b.object_id
21167600
2.2.1 :022 > b = " goodbye!"
" goodbye!"
2.2.1 :023 > b.object_id
21130200
Judith Roth
License
Source code in this card is licensed under the MIT License.
Posted by Judith Roth to makandra dev (2015-11-30 13:44)