From: Rajinder Yadav Date: 2009-10-16T12:51:37+09:00 Subject: Re: deep cloning, how? Robert Klemme wrote: > On 10/15/2009 08:07 PM, Caleb Clausen wrote: >> On 10/14/09, Robert Klemme wrote: >>> On 14.10.2009 19:03, Caleb Clausen wrote: >>> >>>> The documentation of Object#dup seems to suggest that subclasses >>>> should not override dup, preferring to override clone instead. >>> Where do you take that from? In the docs referenced below I cannot find >>> anything like that. The only indication I can see is that #dup uses >>> #initialize_copy and we should probably override that instead of #dup >>> itself. >> >> I'm looking at these 2 sentences: >> >> In general, +clone+ and +dup+ may have different >> semantics in descendent classes. While +clone+ is used to duplicate >> an object, including its internal state, +dup+ typically uses the >> class of the descendent object to create the new instance. >> >> Frankly, I've never been real sure what this is supposed to mean, so >> my reading may well be wrong. In fact, it probably is. >> >> initialize_copy apparently is used by both dup and clone. You're >> right, that should be defined (overridden?) instead of dup/clone >> themselves. I rarely remember that. > > Mee, too. :-) Just for the reference > > irb(main):019:0> class X > irb(main):020:1> def initialize_copy(*a) p [self,a] end > irb(main):021:1> end > => nil > irb(main):022:0> x=X.new > => # > irb(main):023:0> x.dup > [#, [#]] > => # > irb(main):024:0> x.clone > [#, [#]] > => # > > And it's noteworthy that frozen state is only established _after_ > initialize_copy has returned: > Celeb, Robert thanks for bringing this point home. I keep having to update my Ruby notes =) .... let me try the initialize_copy way! > irb(main):025:0> class X > irb(main):026:1> def initialize_copy(old) > irb(main):027:2> @x=1 > irb(main):028:2> end > irb(main):029:1> end > => nil > irb(main):030:0> X.new.freeze.clone > => # > >>> There are more differences namely in the area of frozen and tainted >>> state. >>> >>> http://www.ruby-doc.org/core/classes/Object.html#M000351 >>> http://www.ruby-doc.org/core/classes/Object.html#M000352 >> >> Ah, yes. But only frozen state, not tainted. > > Right you are. > > Kind regards > > robert > -- Kind Regards, Rajinder Yadav http://DevMentor.org Do Good ~ Share Freely