Ruby复制数组数组

[英]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.

Ruby中有没有办法制作多维数组的副本?我的意思是一些内置功能。

When I try to use .dup it just returns reference:

当我尝试使用.dup时,它只返回引用:

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 个解决方案

#1


10  

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)

#2


6  

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 
关注微信公众号

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/05/09/16b8bf50cfbd3c916572069d2addf25f.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com