如何将新哈希插入到ruby中的现有哈希中

时间:2012-03-06 10:51:29

标签: ruby-on-rails ruby hash

我有两个哈希:

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

我需要将其作为

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

2 个答案:

答案 0 :(得分:4)

我想你想要这个:

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

通过这种方式,您将拥有arrayhashes

答案 1 :(得分:1)

Tim指出,r似乎不是哈希,也许你的意思是一个数组,在这种情况下你可以做

r = [p,q]

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