Array overwrite question

jake kaiden wrote in post #1010461:

CC Chen wrote in post #1010408:

If on multi-dimension array?

I try .dup it cant work!!

  what version of ruby are you using, with both 1.8.7 and 1.9.2
Array#dup works for me...

bb = [[1,2], [3,4], [5,6]]
cc = bb.dup

p cc

But of course, the subarrays in cc and the subarrays in bb are the same
objects.

bb = [[1,2], [3,4], [5,6]]
cc = bb.dup
bb[0] << 3
p cc
# [[1, 2, 3], [3, 4], [5, 6]]

You can do the dups for the second level too yourself, or use this deep
copy trick:

cc = Marshal.load(Marshal.dump(bb))

···

--
Posted via http://www.ruby-forum.com/\.