Sunday, September 21, 2008

Copying Objects

When you use =, clone, or dup to copy an object, only the object reference is copied,
not the referenced object itself (Shallow Copy).

In order to do a deep object copy, we can use the marshaling trick by dumping and
loading the object.

For example:

def deepcopy(something)
Marshal.load(Marshal.dump(something))
end

irb>b = "abcd"
=> "abcd"
irb>a = b
=> "abcd"
irb>a.upcase!
=>"ABCD"
irb>b
=>"ABCD" # see how b changes too
irb>b = deepcopy(a)
=>"ABCD"
irb>b.downcase!
=>"abcd"
irb>a
=>"ABCD" # a stayed the same this time

J

No comments: