9.5 Cloning and freezing objects

Cloning objects

What happens when you assign the same object to two different variables? Lets take a look:

Example Code:

Output Window

Oh look! Changing b changed 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 clone method:

Example Code:

Output Window

Note that you need to clone an object usually when you plan to mutate the object in-place. Consider this example:

Example Code:

Output Window

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.

The 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.

Freezing objects

There are occasions when you want to prevent any changes to an object. This is called 'freezing' an object. All objects in Ruby has the freeze method that does this. Let us look at an example where we freeze a string and attempt to modify it later:
Example Code:

Output Window

As you can see, mutating an already frozen object raises an error.

However, this is still possible:

Example Code:

Output Window

The above is perfectly valid. As we have demonstrated in the previous section, variables only store references to object. The freeze method was executed on the actual object and the object remains frozen. However, you can change the variable to refer to a different object anytime - which is what the example above did.

You can use the frozen? method on an object to check whether an object is currently frozen or not.

Let us finish this chapter with a trivial exercise. Add a method frozen_clone to the Object class so that I can get a frozen clone of any object.

Hint

Clone and Freeze!

Output Window

Congratulations, guest!


% of the book completed

or

This lesson is Copyright © 2011-2024 by Jasim A Basheer