I'm looking at some techniques to deep-copy objects in Ruby (MRI 1.9.3).
I came across the following example, but I'm not sure about the #dup
method implementation.
I tested it and it does work, but I don't understand the logical steps of the method, thus I'm not confortable using it in my own code.
Is the statement @name = @name.dup
referring to the iVar inside the copy? How? I can't see it.
Could anyone explain it, please?
Also, are there better ways?
class MyClass
attr_accessor :name
def initialize(arg_str) # called on MyClass.new("string")
@name = arg_str # initialize an instance variable
end
def dup
the_copy = super # shallow copy calling Object.dup
@name = @name.dup # new copy of istance variable
return the_copy # return the copied object
end
end