Is there a way in Ruby to make a copy of multi-dimensional array? I mean some built-in function.
When I try to use .dup it just returns reference:
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
Changes to a copied array do not affect the original one. Copy array. An array is stored in a region of memory. When we modify it, we modify that region of memory. Two array variables can point to the same region. Ruby syntax note. We can copy an array, with slice syntax, to create separate arrays. This can be helpful in recursive methods. Example.
Ruby arrays are ordered, integer-indexed collections of any object. Each element in an array is associated with and referred to by an index. Array indexing starts at 0, as in C or Java.
This Ruby article copies arrays with the slice operator. Changes to a copied array do not affect the original one. An array is stored in a region of memory. When we modify it, we modify that region of memory. Two array variables can point to the same region. We can copy an array, with slice syntax, to create separate arrays.
There are 3 ways to copy arrays : 1 Simply using the assignment operator. 2 Shallow Copy 3 Deep Copy More ...
You need to dup the arrays in the list instead of just the outer one. The easiest way is probably something like
b = a.map(&:dup)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With