ruby - Weird behaviour copying objects -
i'm trying deep re-create object holds 3d array. isn't working expected.
class def initialize @a = [[[1]], [[2]]] end def modify3d @a[0][0] = @a[1][0] end def modify2d @a[0] = @a[1] end def dup re-create = super copy.make_independent! re-create end def make_independent! @a = @a.dup end def show print "\n#{@a}" end end = a.new b = a.dup #a.modify2d b.show a.modify3d b.show
in case b changed modify3d phone call on a.
[[[1]], [[2]]] [[[2]], [[2]]]
if uncomment modify2d line works fine.
[[[1]], [[2]]] [[[1]], [[2]]]
could pls explain happening here?
your re-create isn't deep enough. array#dup duplicates array itself, not array elements. end 2 different arrays still share same elements.
in this answer showed how utilize marshaling deep copy. method work:
def deep_copy(o) marshal.load(marshal.dump(o)) end
deep_copy works object can marshaled. built-in info types (array, hash, string, &c.) can marshaled. object instance variables can marshaled can marshaled.
having defined deep_copy, replace line:
b = a.dup
with this:
b = deep_copy(a)
and ought work expect.
ruby deep-copy
No comments:
Post a Comment