4

Is there an easy way to copy a nested Array so that every object in the array will be a 'dup' of the original? I recently run into this:

irb(main):001:0> a = [[1,2],[3,4]]
=> [[1, 2], [3, 4]]
irb(main):002:0> b = a.dup
=> [[1, 2], [3, 4]]
irb(main):003:0> a[0][1] = 99
=> 99
irb(main):004:0> a
=> [[1, 99], [3, 4]]
irb(main):005:0> b
=> [[1, 99], [3, 4]]
irb(main):006:0> a[0] = [101,102]
=> [101, 102]
irb(main):007:0> a
=> [[101, 102], [3, 4]]
irb(main):008:0> b
=> [[1, 99], [3, 4]]

So while the first level of arrays in a were individual objects, their content were not, a[0][1] is still equal to b[0][1]. A general solution don't even have to know how deeply an array is nested. Walking through every object and make it a dup of itself sounds a bit brute-force to me.

Alexey Lebedev
  • 11,988
  • 4
  • 39
  • 47
karatedog
  • 2,508
  • 19
  • 29
  • In an ideal world, you wouldn't need to duplicate it, because you wouldn't do any modification of objects. However, if you're working with a legacy app where object modification goes on, it's a legitimate question. – Andrew Grimm Mar 13 '11 at 22:19
  • I'm working on some chaotic function visualization, where one value in the array is depending on the previous value and calculation is iterated a few times. I have to do the calculation atomic on the whole array level (which represents the visible area), so I have 2 arrays and I make calculations from the first, and put the result to the second (in the same position), and when the current iteration ends, I should make the 'present' array a 'previous' one, this when a simple Pascal-like array copy needed. – karatedog Apr 01 '11 at 21:41

1 Answers1

4
b = Marshal.load(Marshal.dump(a))
Alexey Lebedev
  • 11,988
  • 4
  • 39
  • 47