Question

I have a hash: hash1

hash1 = Hash.new

I have another hash: hash2

hash2 = Hash.new

I added the following key-value pair in it:

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

Now, I want to have "key1" in hash1 which will be associated with "k1", "k2", "k3" of hash2.

I want something of this sort:

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

How do I associate hash1 and hash2.

Was it helpful?

Solution 2

Yes do then as below :

hash1 = Hash.new

hash2 = Hash.new

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

p hash1

OTHER TIPS

This will do:

hash1['key1'] = hash2

You simply define a key in your new hash and as a value you just pass in the hash you created earlier:

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

Or if you prefer to do it via store method, just pass in the h2 as an argument:

h1["key1"] = h2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top