Duplicating and cloning objects in Ruby

Objects can be duplicated in Ruby if you would like to retain the state of the original object, but perform destructive actions on another object. The following example illustrates that dup creates a separate copy of an object with different object id.

>> c = "cereal"
=> "cereal"
>> c.object_id
=> 70248305145860
>> c.dup.object_id
=> 70248305133180

When the object is duplicated, destructive actions can be performed and the original object will be unchanged.

>> c = "cereal"
=> "cereal"
>> c.dup.upcase!
>> c
=> "cereal"

The clone method is similar to dup, but if you dup a frozen object, but duplicate is not frozen. If you clone a frozen object, the duplicate is frozen.

>> dog = "fido"
=> "fido"
>> dog.freeze
=> "fido"
>> dog.dup.frozen?
=> false
>> dog.clone.frozen?
=> true

The freeze method prevents an object from being mutated.

>> abc = "simple as 123"
=> "simple as 123"
>> abc.freeze
=> "simple as 123"
>> abc.upcase!
RuntimeError: can't modify frozen String

However, frozen objects, can be reassigned to reference other objects:

>> var = "0 is TRUE!"
=> "0 is TRUE!"
>> var.freeze
=> "0 is TRUE!"
>> var = "recursion is cool"
=> "recursion is cool"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s