Posted over 3 years ago. Visible to the public.

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

This looks like it is safe to use:

Copy
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!

Copy
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:

Copy
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:

Copy
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

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Judith Roth
Last edit:
over 3 years ago
by Judith Roth
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Judith Roth to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more