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
4

2 回答 2

15

您需要复制列表中的数组,而不仅仅是外部数组。最简单的方法可能是

b = a.map(&:dup)
于 2012-05-09T11:48:12.113 回答
8

编组应该可以解决问题:

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 
于 2012-05-09T11:14:18.127 回答