2012-10-12 37 views
3

有人可以解釋這一點嗎?如何更改ruby二維數組中的一個單元格?

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列?

回答

5
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 
+0

那麼,我們該如何評估一個特定的細胞呢? –

+0

@ 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 
相關問題