如何在Ruby的二维数组中更改一个单元格?

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列中的所有单元格?
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

那么,我们如何为特定单元格赋值? - Prasad Surase
@surase.prasad 试试我的函数版本 :) - xdazz

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接