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"

?

-- 
Hassle-free packages for Ruby?
RPA is available from http://www.rubyarchive.org/