Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby copy an array of arrays

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
like image 781
Victor Marchuk Avatar asked May 09 '12 11:05

Victor Marchuk


People also ask

What happens when you copy an array in Ruby?

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.

What is an array in Ruby?

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.

How to copy arrays with the slice operator in Ruby?

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.

How can I copy an array?

There are 3 ways to copy arrays : 1 Simply using the assignment operator. 2 Shallow Copy 3 Deep Copy More ...


2 Answers

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)
like image 175
Sionide21 Avatar answered Sep 22 '22 06:09

Sionide21


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 
like image 34
dexter Avatar answered Sep 23 '22 06:09

dexter