2011-06-24 62 views
0

我誤會陣列行爲紅寶石陣奇怪的行爲

當我創造了這個矩陣

matrix, cell = [], []; 5.times { cell << [] } # columns 
3.times { matrix << cell } # lines 
matrix 
sample_data = (0..5).to_a 
matrix[1][2] = sample_data.clone 
matrix.each { |line| puts "line : #{line}" } 

我有這樣的結果

line : [[], [], [0, 1, 2, 3, 4, 5], [], []] 
line : [[], [], [0, 1, 2, 3, 4, 5], [], []] 
line : [[], [], [0, 1, 2, 3, 4, 5], [], []] 

而不是預期的結果

line : [[], [], [], [], []] 
line : [[], [], [0, 1, 2, 3, 4, 5], [], []] 
line : [[], [], [], [], []] 

什麼錯了?

回答

6

問題是伴您行:

3.times { matrix << cell } 

您使用的是同一個對象cell作爲三大行的matrix

關鍵是Array是一個可變對象。即使你修改它,它的身份也不會改變。 cell的三次出現都指向相同的實例(對象)。如果您通過一次訪問並修改它,其他事件將反映出這種變化。

如果更改此行:

3.times { matrix << cell.dup } 

那麼你會得到期望的結果。

+0

或者因爲單元格是空的,只需使用新的[]而不是指定單元格......'3times {matrix << []}' – DGM

2

您將相同的對象(單元格)放入矩陣中三次。

這將解決你的bug:

3.times { matrix << cell.clone } # lines 

...但你可能要解釋你想使用此代碼來解決,因爲可能會有更好的辦法是什麼問題...