我有一個散列,其中鍵是一個字符串,值是一個字符串的數組。 我想是這樣的:紅寶石數組哈希
{"k1"=>["v1", "v2"], "k2"=>["v3", "v4"]}
我只有一個哈希和一個陣列來實現這一點。我已經編寫這樣的事情:
hash1 = Hash.new
arr = Array.new
arr.push "v1"
arr.push "v2"
hash1["k1"] = arr
#hash is like this: {"k1"=>["v1", "v2"]
#Now I clear the array to read the new values
arr. clear
arr.push "v3"
arr.push "v4"
hash1["k2"] = arr
puts hash1
#Output: {"k1"=>["v3", "v4"], "k2"=>["v3", "v4"]}
#Notice that k1's value also got updated
然後,我改變了一行:
hash1 = Hash.new
arr = Array.new
arr.push "v1"
arr.push "v2"
hash1["k1"] = arr
arr = [] # ** This is the only changed line. Now k1's value is correct. **
arr.push "v3"
arr.push "v4"
hash1["k2"] = arr
puts hash1
#Output: {"k1"=>["v1", "v2"], "k2"=>["v3", "v4"]} (which I wanted)
是否有人可以解釋我這樣做是如何發生的?我對Ruby很新。理想情況下,解決這個問題的正確方法是什麼?
「我只有一個散列和一個數組來執行此操作。不在你的第二個例子中。你有兩個數組。 – Ajedi32
'{}'幾乎總是比'Hash.new'更好,'[]'更好''Array.new'。 – tadman
@tadman爲什麼更好?這僅僅是爲了可讀性嗎?還是還有其他好處? –