Ruby copies an array of arrays

Is there a way in Ruby to make a copy of a multidimensional array? I mean some built-in function.

When I try to use .dup, it just returns a link:

irb(main):001:0> a = [[1,2,3], [4,5,6]] => [[1, 2, 3], [4, 5, 6]] irb(main):002:0> b = a.dup => [[1, 2, 3], [4, 5, 6]] irb(main):003:0> b[0][0] = 15 => 15 irb(main):004:0> a == b => true 
+4
source share
2 answers

You need to combine the arrays in the list, not just the external one. The easiest way is something like

 b = a.map(&:dup) 
+9
source

Marshaling should do the trick:

 jruby-1.6.7 :001 > a = [[1,2,3], [4,5,6]] => [[1, 2, 3], [4, 5, 6]] jruby-1.6.7 :002 > b = Marshal.load( Marshal.dump(a) ) => [[1, 2, 3], [4, 5, 6]] jruby-1.6.7 :004 > a == b => true jruby-1.6.7 :005 > b[0][0] = 15 => 15 jruby-1.6.7 :006 > a == b => false 
+6
source

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


All Articles