Read more

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

Judith Roth
November 30, 2015Software engineer at makandra GmbH

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!"
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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
Posted by Judith Roth to makandra dev (2015-11-30 14:44)