有人可以解释一下吗?
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"]]
我的理解是块[1] [2]只更改第1行第2列的单元格,但为什么它会更改第2列中的所有单元格?
答案 0 :(得分: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
答案 1 :(得分: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