Ruby 关于嵌套数组

africwildman · 2015年03月19日 · 最后由 africwildman 回复于 2015年03月19日 · 2145 次阅读
a=Array.new 6,[]
a[0].push 1,2,3,4,5

我以为 a 的结果应该是 [[1,2,3,4,5],[],[],[],[],[]] 结果是 [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]] 要得到 [[1,2,3,4,5],[],[],[],[],[]] 需要 a[0]= 1,2,3,4,5 不明白为什么。

又看了一下文档,像楼主这样声明是有问题的:

Note that the second argument populates the array with references to the same object. Therefore, it is only recommended in cases when you need to instantiate arrays with natively immutable objects such as Symbols, numbers, true or false.

To create an array with separate objects a block can be passed instead. This method is safe to use with mutable objects such as hashes, strings or other arrays:

因此

a = Array.new(6) { [] }

才是楼主需要的

a[0]=1,2,3,4,5中的=号赋值其实是更改了a[0]的引用,所以不会影响原来的引用。

原来如此,数组内容都指向了同一个位置。 #2 楼 @loveltyoic

需要 登录 后方可回复, 如果你还没有账号请 注册新账号