From: "David A. Black" Date: 2008-05-06T00:38:19+09:00 Subject: Re: Recursive dup --1926193751-1727503153-1210001900=:24008 Content-Type: MULTIPART/MIXED; BOUNDARY="1926193751-1727503153-1210001900=:24008" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --1926193751-1727503153-1210001900=:24008 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE Hi -- On Mon, 5 May 2008, I=C3=B1aki Baz Castillo wrote: > Hi, it seems that "dup" method is not recursive, so if we do: > obj_b =3D obj_a.dup > then all the attributes of obj_b will be a exact copy of attributes of > obj_a, and not references. > > But if an attribute of obj_a is an object containing objects inside > then those will be referenced and not copied. This is: > > -------------------------------- > class A > =09attr_accessor :att > end > > class Obj > =09attr_accessor :kk > end > > obj =3D Obj.new > obj.kk =3D "KAKA1" > a=3DA.new > a.att=3Dobj > > a > =3D> #> > > b=3Da.dup > =3D> #> > > b.a.kk=3D"KAKA2" > > a > =3D> #> > ----------------------------------------- > > So finally, an attribute of an attribute of "a" is been modified when > modifying "b". > I know that I should personalize "dup" method for class A, but is not > any other way? Does exist any automatic way of doing it? > I expect some method "dup_recursive" that looks for objects into > attributes recursively and clones them instead of reference. > > Is there something as it? The most common idiom for a deep clone is: new_obj =3D Marshal.load(Marshal.dump(old_obj)) David --=20 Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin INTRO TO RAILS June 24-27 London (Skills Matter) See http://www.rubypal.com for details and updates! --1926193751-1727503153-1210001900=:24008-- --1926193751-1727503153-1210001900=:24008--