From: Robert Klemme Date: 2009-10-14T19:57:55+09:00 Subject: Re: deep cloning, how? 2009/10/14 Rajinder Yadav : > I am trying to figure out how to perform a deep clone > > > class A >   attr_accessor :name > end > > a1 = A.new > a1.name = "yoyoma" > a2 = a1.dup > a1.name.chop! > puts a2.name > > > I found the following way to write a deep clone method > > class A >  attr_accessor :name >  def dup >     Marshal::load(Marshal.dump(self)) >  end > end > > If I wanted to write my own specialize deep_cloner, how would I do this. If > I try the obvious way to do it, > > def dup >   @name = self.name.dup > end No, this is by far not the obvious way since you would at least have to make sure there is a copy of self and this is returned from dup. I would rather do def dup copy = super copy.name = @name.dup copy end or even def dup self.class.new(@name.dup) end Although that approach is fragile depending on the code in #initialize. > I get an error when 'puts a2.name' is executed saying: > > NoMethodError: undefined method `name' for "yoyom":String > > > Can someone explain what's going on when dup is called. What gets passes to > dup (i assume self) and why my code is wrong? Hope the above sheds some light. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/