Siva sakthi Karthik
Siva sakthi Karthik

Reputation: 33

How to insert a new hash into existing hash in ruby

I have two hashes:

p = {"name"=>"TRICHI", "subdistrict"=>{"WANDIWASH"=>"1234"}}
q = {"name"=>"VELLORE", "subdistrict"=>{"WANDIWASH"=>"4183"}}

I need to make this as

r = [{"name"=>"VELLORE", "subdistrict"=>{"WANDIWASH"=>"4183"}}, 
    {"name"=>"TRICHI", "subdistrict"=>{"WANDIWASH"=>"1234"}}] 

Upvotes: 1

Views: 4078

Answers (2)

Arnaud
Arnaud

Reputation: 17737

As Tim pointed, r doesn't seem to be a Hash, maybe you meant an Array, in which case you can do

r = [p,q]

or

r = []
r << p
r << q
.. keep going for any other entry you want to push into r

Upvotes: 1

Simon Woker
Simon Woker

Reputation: 5034

I guess you want this:

r = [] << p << q
# or r = [p, q]
# either way you'll get:
#  [ {"name"=>"VELLORE", "subdistrict"=>{"WANDIWASH"=>"4183"}},
#    {"name"=>"TRICHI", "subdistrict"=>{"WANDIWASH"=>"1234"}}  ]

This way you will have an array with 2 hashes.

Upvotes: 4

Related Questions