How to copy nested arrays and make sure that the copy is a complete duplicate of the original

Is there an easy way to copy a nested array so that every object in the array is "dup" of the original? I recently came across 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, although the first level of arrays in a were individual objects, their contents were not, a[0][1] is still equal to b[0][1] . The general solution does not even have to know how deeply the array is nested. Walking through each object and making it an understudy sounds a little brute force to me.

+4
source share
1 answer
 b = Marshal.load(Marshal.dump(a)) 
+3
source

Source: https://habr.com/ru/post/1343442/


All Articles