我有一个散列,其中键是一个字符串,值是一个字符串的数组。 我想是这样的:红宝石数组哈希
{"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为什么更好?这仅仅是为了可读性吗?还是还有其他好处? –