Ruby:赋值给数组的元素

时间:2016-09-13 13:32:37

标签: ruby variable-assignment

我是初学者,我想创建一个矩阵。例如:

0 1 1
1 1 1
1 1 2

irb(main):001:0> t = [[1]*3]*3
=> [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
irb(main):002:0> (0...3).each do |x| t[x][x]=x end
=> 0...3
irb(main):003:0> t
=> [[0, 1, 2], [0, 1, 2], [0, 1, 2]] # why all values changed?

怎么了?

1 个答案:

答案 0 :(得分:2)

构造数组的方式不会为每一行创建新数组,但引用所有行的相同数组:

t.each do |row|
  p row.object_id
end

# 70325094342320
# 70325094342320
# 70325094342320

与以下内容相同:

a = [1, 1, 1]
t = [a, a, a]

尝试这样做可以看出差异:

t = [[1] * 3, [1] * 3, [1] * 3]