13

我有一个哈希,其中 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 很陌生。理想情况下,编码这个问题的正确方法是什么?

4

2 回答 2

14

这应该向您展示正在发生的事情(object_id是您的朋友)。(我在 Object_id 中插入了一个下划线,以便更容易看到差异。)

hash1 = {}            # => {} 
arr = ["v1", "v2"]    # => ["v1", "v2"] 
arr.object_id         # => 7016637_4343580 
hash1["k1"] = arr     # => ["v1", "v2"] 
hash1                 # => {"k1"=>["v1", "v2"]}
hash1["k1"].object_id # => 7016637_4343580 
arr.clear             # => [] 
arr.object_id         # => 7016637_4343580 
arr << "v3" << "v4"   # => ["v3", "v4"] 
arr.object_id         # => 7016637_4343580 
hash1["k2"] = arr     # => ["v3", "v4"] 
hash1                 # => {"k1"=>["v3", "v4"], "k2"=>["v3", "v4"]} 
hash1["k1"].object_id # => 7016637_4343580 
hash1["k2"].object_id # => 7016637_4166580 

arr = []              # => [] 
arr.object_id         # => 7016637_4036500 
arr = ["v5", "v6"]    # => ["v5", "v6"] 
arr.object_id         # => 7016637_3989880 
hash1                 # => {"k1"=>["v3", "v4"], "k2"=>["v3", "v4"]} 
hash1["k1"].object_id # => 7016637_4343580 
hash1["k2"] = arr     # => ["v5", "v6"] 
hash1                 # => {"k1"=>["v3", "v4"], "k2"=>["v5", "v6"]} 
hash1["k1"].object_id # => 7016637_4343580 
hash1["k2"].object_id # => 7016637_3989880 
于 2013-09-27T19:40:35.720 回答
3

您保存在散列上的数组仍然被arr如此清楚地引用,arr.clear并且使用arr.push会清理并将新值添加到保存在散列上的数组。但是arr = []arr现在将引用一个新数组,该数组与保存在哈希中的数组不同。

你可以简单地添加一个新数组来散列:

hash1["k2"] = ["v3", "v4"]

或者

hash1["k2"] = %w[v3 v4]
于 2013-09-27T18:50:10.967 回答