阵列行为不端 [英] Arrays misbehaving

查看:145
本文介绍了阵列行为不端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的code:

# 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]

那么,为什么会这样?

So why is that?

推荐答案

在注释行被分配三个的相同的参考的到阵列,所以更改一个阵列将在其他引用传播吧。

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)}

在传递一个块( {...} 做...结束),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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆