From: Justin Johnson Date: 2002-08-07T12:03:09+09:00 Subject: Re: Dup and Clone I can't think of a good reason that there isn't a deep copy supplied. The marshal solution works but is a bit of a sledgehammer approach. If an object is capable of cloning itself then you'd think a deep copy would be easy. Except... how would you efficiently avoid cycles? Marshal does it by remembering what it's marshalled - like any persistency system. To do this you'd can use hash table (addr_hash) that held .. The basic algorithm is something like: deep_copy( object ) if object is not in addr_hash newaddress = clone object add_hash for each child object child = deep_copy( child ) end end return newaddress end Perhaps now I can see why this was avoided.... -- Justin Johnson "Patrick Bennett" wrote in message news:3D50845B.9040305@inin.com... > > > Joel VanderWerf wrote: > > > Patrick Bennett wrote: > > > >> Tom Gilbert wrote: > >> > >>> Can't you deep copy using Marshal? > >>> > >>> a = Marshal.restore(Marshal.dump(b)) > >>> > >> I guess(?) It seems like a pretty major hack though. It really > >> should be built into the language, or into the standard > >> library distribution. > > > > > > I agree it seems hackish to generate strings just to deep-copy > > objects, but there is an advantage to using Marshal: it guarantees > > that this deep copy operation has *exactly* the same semantics as > > sending objects to disk or to other processes. > > Good point. I guess I would (well, me at leats) probably just add a > deepCopy method to Object that used marshall to accomplish it. > class Object > def deepCopy > return Marshal.restore(Marshal.dump(self)) > end > end > > a = "Tim" > b = a.deepCopy > b[0] = 'J' > p a, b > > Strings are admittedly a bad example (because dup or clone for a string > works just fine), but it's an obvious litmus test. > > The thing is, if it's so easy to do, and it seems to 'work,' why isn't > it already defined in Ruby? > Any experts out there care to shed some light on the subject to a Ruby > newbie? > > > What if some class defined its own _dump and _load (maybe because the > > objects have a reference to some large shared data structure), but > > forgot to do whatever it has to do so that deep copy follows the same > > principle? > > Honestly, I think it would be far more likely for the 'average' class to > >not< have custom _dump/_load methods > >