The reason for that is that variables are merely references to data. Variables are stored in memory; variables keep address of where they are located in a memory. So when you do:
a = b
Those two variables point to the same memory location, hence if you alter a
, b
is altered as well because it is the same object.
There are a few ways to force Ruby to create another copy of the object. The most popular one is the dup
method mentioned by LBg. Note however that it is only creating a shallow copy. If you run:
a = ['foo','bar', []]
b = a.dup
a << 'blah'
b #=> ['foo', 'bar', []] as expected but
b[3] << blah
a #=> ['foobar', 'bar', ['blah]]
The reason for that is that array is in fact an array of references and nested array has not been duplicated when performing dup
, so they are the same object.
To create a deep copy of an object, you can use the Marshall module:
b = Marshal.load(Marshal.dump(a))
However, usually you don't really need to do this. Also, some objects cannot be duplicated (e.g. symbols).