Gotcha in Ruby for PHP Developers with multiple assignments of array to variables

The more I work with Ruby and Ruby on Rails, the more I begin to understand (though not necessarily agree with) a lot of the vitriol that has been aimed at PHP over the years by developers using other more rigorous languages.

A few weeks back I ran into this little speed bump while working with Ruby on Rails, where I was  trying to do a multiple assignment like this

x = y = z = []

Most seasoned Rubyists will be waving their arms around and yelling “NOOOOOO!!!”
But coming from a PHP background this seemed perfectly okay to me.

Let me go off on a (relevant) tangent here and show you how the PHP code for this assignment would work

$x = $y = $z = array();
$x = 'me';
print_r($x);
print_r($y);
print_r($z);

the output from this is

me Array() Array()

Notice how the variables $y and $z remain arrays?
Now lets look at the same ruby code.

multiple assignment of array to variables in ruby

You can see that when we do an assignment of

x = y = z = []

ALL the variables point to the same array, so changing one item, changes all the other variables!

This is because arrays, hashes and certain objects are passed by reference not by value.

I say “certain” objects because the assignment

var1 = var2 = "you"

… doesn’t work the same way – as you can see above – even though the quoted string “you” is an object in Ruby.

So be careful PHPsters … this cost me a couple of hours in my project.
Hopefully you can skate around this one if you come across it.