-2

我有一个哈希:hash1

hash1 = Hash.new

我有另一个哈希:hash2

hash2 = Hash.new

我在其中添加了以下键值对:

hash2.store("k1","v1")
hash2.store("k2","v2")
hash2.store("k3",["v3","v4"])

现在,我想"key1"hash1其中将与"k1", "k2", "k3"of相关联hash2

我想要这样的东西:

{"key1"=>{"k1"=>"v1", "k2"=>"v2", "k3"=>["v3", "v4"]}}

如何关联 hash1 和 hash2。

4

3 回答 3

1

这将做:

hash1['key1'] = hash2
于 2013-09-26T10:40:22.760 回答
0

是的,然后如下:

hash1 = Hash.new

hash2 = Hash.new

hash2.store("k1","v1")
hash2.store("k2","v2")
hash2.store("k3",["v3","v4"])
hash1['key1']= hash2

p hash1
于 2013-09-26T10:40:40.523 回答
0

您只需在新散列中定义一个键,并将其作为值传入您之前创建的散列中:

h2 = {k1: "v1", k2: "v2", k3: ["v3","v4"]}
h1 = {key1: h2}
# => {:key1=>{:k1=>"v1", :k2=>"v2", :k3=>["v3", "v4"]}}

或者,如果您更喜欢通过 store 方法执行此操作,只需传入h2作为参数:

h1["key1"] = h2
于 2013-09-26T10:45:29.677 回答