Hi, it seems that “dup” method is not recursive, so if we do:
obj_b = 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
attr_accessor :att
end
class Obj
attr_accessor :kk
end
obj = Obj.new
obj.kk = “KAKA1”
a=A.new
a.att=obj
a
=> #<A:0xb7bf6de8 @att=#<Obj:0xb7c0dcf0 @kk=“KAKA1”>>
b=a.dup
=> #<A:0xb7becd97 @att=#<Obj:0xb7c0dcf0 @kk=“KAKA1”>>
b.a.kk=“KAKA2”
a
=> #<A:0xb7bf6de8 @att=#<Obj:0xb7c0dcf0 @kk=“KAKA2”>>
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?
Thanks a lot.
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Iñaki Baz C. wrote:
| 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.
If your storage of objects can be enumerated, you could use .each,
duplicate the objects you store, and re-store them.
That doesn’t seem terribly efficient, though, so proceed with caution
(but it may get you started in the right direction :).
Phillip G.
Twitter: twitter.com/cynicalryan
Blog: http://justarubyist.blogspot.com
Make sure comments and code agree.
~ - The Elements of Programming Style (Kernighan & Plaugher)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
iEYEARECAAYFAkgfFI4ACgkQbtAgaoJTgL9g/wCghdYgjUs5o0cNsmxItj8yHOT9
pKEAnAxds5jvXuulwEphsjRtCx1UFwCP
=TiIJ
-----END PGP SIGNATURE-----
Hi –
On Mon, 5 May 2008, Iñaki Baz C. wrote:
attr_accessor :att
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 = Marshal.load(Marshal.dump(old_obj))
David
2008/5/5, David A. Black [email protected]:
The most common idiom for a deep clone is:
new_obj = Marshal.load(Marshal.dump(old_obj))
It’s simply GREAT !!!
Thanks a lot !