8

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

2 Answers 2

15

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I suppose this only works for 1 extra dimension. What about N-dimensions? I suppose dup should be applied recursively on each object.
8

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.