迭代時,我每次都將一些數據保存爲哈希。在同一個循環中,我將散列推送到一個數組中。Ruby - 將哈希推向陣列
下面的代碼不起作用,最後一個哈希對象會覆蓋數組中的所有其他哈希對象。
playlists = []
aPlaylist = {}
while (count < 3)
#some code... produces the hash "aPlaylist"
playlist << aPlaylist
end
下面的代碼確實有效。爲什麼,還有什麼區別?
playlists = []
while (count < 3)
aPlaylist = {}
#some code... produces the hash "aPlaylist"
playlist << aPlaylist
end
這裏是正確與錯誤輸出(轉換成CSV): http://imgur.com/a/rjmBA。
_「最後散列對象覆蓋數組中的所有其他數據「_ - 你能顯示錯誤的結果嗎? – Stefan
這完全取決於您遺漏的「某些代碼」。 –
我用圖像更新了問題。 @JörgWMittag我不這麼認爲,其他答案解釋了原因。 – Emre