我有一个哈希,其中 key 是一个字符串,而 value 是一个字符串数组。我想要这样的东西:
{"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 很陌生。理想情况下,编码这个问题的正确方法是什么?