What happens when you assign the same object to two different variables? Lets take a look:
Oh look! Changing
a as well! This is because variables store only references to objects. When assigning one variable to another, Ruby does not copy the actual object - only the references are copied.
To create an independent copy of an object, you should use the
Note that you need to clone an object usually when you plan to mutate the object in-place. Consider this example:
If you look at the example above, you'll see that reassigning
foo with a new object does not change the
foos array. This is because
foos holds the reference to the original "foo" string.
foo = foo.upcase simply changes the object that the variable
foo refers to. The original object remains as is since
foo.upcase returns a new string object.
In the case of
bar, we used the
upcase! command that changes the object in-place and thus the change is reflected in all objects that holds a reference to the object.
clone method should be used when you need to mutate an object due to performance reasons. This ensures that the original object is not affected. Mutation of objects results in brittle code and should be avoided.