3

有人可以解释一下吗?

def digit_block(size = 1)
  col = 2 + 1*size
  row = 1 + 2*size
  r = []
  for i in 0...col
    r.push ' '
  end
  a = []
  for i in 0...row
    a.push r
  end
  a
end

block = digit_block
puts block.inspect
block[1][2] = 'x'
puts block.inspect

输出:

[[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
[[" ", " ", "x"], [" ", " ", "x"], [" ", " ", "x"]]

我的理解是 block[1][2] 仅更改第 1 行第 2 列的单元格,但为什么它会更改第 2 列中的所有单元格?

4

2 回答 2

6
  for i in 0...row
    # you are pushing the same array object to an array
    a.push r
  end

所以里面的每个元素block都是同一个对象。

block[0] === block[1]  # true
block[1] === block[2]  # true

更新:

您需要为每个元素创建一个新数组,您的代码可以重写如下:

def digit_block(size = 1)
  Array.new(1 + 2*size){Array.new(2 + size){' '}}
end
于 2012-10-12T05:19:57.870 回答
0

您只生成一个数组r。即使您在多个地方使用它,它们的身份也是相同的。如果您在一个位置更改它,它会影响其他位置的同一对象。要回答标题中的问题,您需要为每一行创建一个不同的数组。

def digit_block(size = 1)
  col = 2 + 1*size
  row = 1 + 2*size
  a = []
  for i in 0...row
    # For every iteration of the loop, the code here is evaluated,
    #  which means that the r is newly created for each row.
    r = []
    for i in 0...col
      r.push ' '
    end
    a.push r
  end
  a
end
于 2012-10-12T05:28:43.103 回答