From: Robert Klemme Date: 2007-06-06T00:00:17+09:00 Subject: Re: Deep Copy On 05.06.2007 16:45, Michael Artz wrote: > I'm needing to implement a deep copy operation on a couple of objects, > and was wondering if there was a "best practices" for this sort of > thing. I've seen the Marshal.load(Marshal.dump()) idiom, but I'm using > singleton classes which can't be dumped. It seems they can be dumped - but you get another instance: irb(main):001:0> require 'singleton' => true irb(main):002:0> class Foo irb(main):003:1> include Singleton irb(main):004:1> end => Foo irb(main):005:0> Foo.instance => # irb(main):006:0> Foo.instance => # irb(main):007:0> Marshal.dump(Foo.instance) => "\004\bo:\bFoo\000" irb(main):008:0> Marshal.load(Marshal.dump(Foo.instance)) => # irb(main):009:0> Marshal.load(Marshal.dump(Foo.instance)).object_id => 1065153200 irb(main):010:0> Foo.instance.object_id => 1065007570 irb(main):011:0> > So I'm implementing my deep > copy similar to: > > def deep_copy > other = self.clone > other.instance_var_1 = self.instance_var_1.clone > other.instance_var_2 = self.instance_var_2.deep_copy > other > end > > where some of the instance variables are objects for which I've written > a deep_copy method. > > The biggest problem with this method (that I can see), is that all of > the attributes of the object need to be publically writable, which is > undesirable. Is there a better way to do this sort of thing? You can use #instance_variable_get and #instance_variable_set to access them. Did you consider overriding #dup and / or #clone for this? Typically you would not want a cloned / duped instance to refer to the original instance's instance variables (at least if they are mutable like collections, strings and other objects). Kind regards robert