-2

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.

Anushka
  • 61
  • 6

3 Answers3

1

This will do:

hash1['key1'] = hash2
Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
0

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
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
0

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
sawa
  • 165,429
  • 45
  • 277
  • 381
Ruslan
  • 1,208
  • 3
  • 17
  • 28