Object Manipulations in Ruby
Ruby allows you to freeze objects and stop you from being able to modify it. However, values are modifiable. Example of such freeze is as following.
my_array = [[1,2],[2,3]].freeze
my_array << [4,5] //produces an error specifying that frozen array can be modified
my_array[1]<<3 //will add new value to first array [1,2,3] without problems.
Frozen objects can be useful for multithreaded code or in preventing future modifications to a frozen class.
Ruby allows to make a copy of the existing object by calling Object.clone method on it.
my_string = “test string”
my_string2 = my_string.clone
In addition to clone, Ruby language has Object.dup method for copying objects. The difference between the two is in a way copy is made. Clone makes a copy of the metaclass and instantiate actual copy instead of instantiating the original class. As a result, you may use dup if you want to make unfrozen copy of a frozen object. Both of these methods create shallow copy, so that you may end up with two objects whose instances point to the same instance variables.
Example of this is presented below
class MyClass
attr_reader :string
def initialize(string)
@string = string
end
end
my_string1 = MyClass.new(‘String’)/
my_string2 = my_string1.dup
my_strgin3 = my_string1.clone
my_string1.string[0] = ‘Z’
my_string2 and my_string3 will print out Ztring.. so you can see how this can be dangers if caution is not applied with both of these methods.
Please note that cloning or duplicating will not run initialize code for each instantiated object. In order to do that you’ll need to add initialize_copy method.