数组行为异常 [英] Arrays misbehaving
本文介绍了数组行为异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码如下:
# a = Array.new(3, Array.new(3))
a = [[nil,nil,nil],[nil,nil,nil]]
a[0][0] = 1
a.each {|line| p line}
输出:
[1, nil, nil]
[nil, nil, nil]
但使用注释行:
[1, nil, nil]
[1, nil, nil]
[1, nil, nil]
那是为什么?
推荐答案
注释行将三个相同引用分配给数组,因此对一个数组的更改将传播到其他引用到它.
The commented line is assigning three of the same reference to the array, so a change to one array will propagate across the other references to it.
对于 2 个数组与 3 个数组,这只是第一行指定 3 作为其第一个参数并仅在第二行中指定 2 个数组文字的问题.
As for the 2 arrays vs 3, that's simply a matter of the first line specifying 3 as its first parameter and only specifying 2 array literals in the second line.
在没有任何共享引用的情况下创建嵌套数组:
To create the nested arrays without having any shared references:
a = Array.new(3) {Array.new(3)}
当传入一个块({...}
或 do ... end
)时,Array.new 会调用这个块来获取每个元素的值数组.
When passed a block ({...}
or do ... end
), Array.new will call the block to obtain the value of each element of the array.
这篇关于数组行为异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文