On Sat, 11 Dec 2004 19:03:22 +0900
Mauricio Fern?ndez <batsman.geo / yahoo.com> wrote:

> On Sat, Dec 11, 2004 at 04:59:10AM +0900, Brian Schr?der wrote:
> > Hello Group,
> > 
> > I sometimes which to make a deep copy of an object. I know I could use
> > Marshal, but thats slow so I want to write a routine #deep_copy. (Or should
> > I overwrite#dup ?)
> > 
> > Now the question is, how do you write those. I could use this:
> > 
> > class A
> >   ...
> >   def deep_copy
> >     result = self.dup
> >     result.field1 = self.field1.deep_copy
> >     ...
> >   end
> > end
> > 
> > or
> > 
> > class A
> >   def initialize(field1 = 'default value', ...)
> >     @field1 = field
> >     ...
> >   end
> > 
> >   def deep_copy
> >     self.new(@field1.deep_copy)
> >   end
> > end
> > 
> > Which allows me to use instance variables.
> > 
> > Is there something more elegant. What do you prefer? Am I on the right
> > track?
> 
> Have you considered the somewhat contrived
> 
> class A; attr_accessor :a; end; 
> a = A.new
> a.a = a
> 
> or more realistically
> 
> class A; attr_accessor :children; def add(name); (@children ||= []) <<
> C.new(name, self) end; end class C; def initialize(name, parent); @name,
> @parent = name, parent end end A.new.add "foo"
> 
> ?
> 

Yes, my structures are not cyclic.

Regards,

Brian

-- 
Brian Schr?der
http://www.brian-schroeder.de/