Ruby 关于嵌套数组

africwildman · March 19, 2015 · Last by africwildman replied at March 19, 2015 · 2145 hits
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

You need to Sign in before reply, if you don't have an account, please Sign up first.