Reputation: 13
I have 2 hashes of hashes that I need to combine on values using Ruby
hoh = Hash.new
hoh = {"bob::params::search_vol_grp"=>{2=>{"search_group_id"=>2, "vol_ids"=>"2,627,628", "num_shards"=>32, "num_replicas"=>1}, 3=>{"search_group_id"=>3, "vol_ids"=>"3,629,630", "num_shards"=>32, "num_replicas"=>1}, 4=>{"search_group_id"=>4, "vol_ids"=>"4,631,632", "num_shards"=>32, "num_replicas"=>1}}
hob = Hash.new
hob = {"bob::params::search_q_broker"=>{2=>{"master_host"=>"hq01p1", "master_port"=>"61616", "slave_host"=>"hq01p2", "slave_port"=>"61616"}, 3=>{"master_host"=>"hq01p1", "master_port"=>"61616", "slave_host"=>"hq01p2", "slave_port"=>"61616"}, 4=>{"master_host"=>"hq01p1", "master_port"=>"61616", "slave_host"=>"hsq01p2", "slave_port"=>"61616"}}
What I'd like to end up with is the following -
hon = Hash.new
hon = {"bob::params::search"=>{2=>{"master_host"=>"hq01p1", "master_port"=>"61616", "slave_host"=>"hq01p2", "slave_port"=>"61616", "search_group_id"=>2, "vol_ids"=>"2,627,628", "num_shards"=>32, "num_replicas"=>1}, 3=>{"master_host"=>"hq01p1", "master_port"=>"61616", "slave_host"=>"hq01p2", "slave_port"=>"61616", "search_group_id"=>3, "vol_ids"=>"3,629,630", "num_shards"=>32, "num_replicas"=>1}, 4=>{"master_host"=>"hq01p1", "master_port"=>"61616", "slave_host"=>"hq01p2", "slave_port"=>"61616", "search_group_id"=>4, "vol_ids"=>"4,631,632", "num_shards"=>32, "num_replicas"=>1}}
I've tried various attempts at using merge and merge! but none of yielded the end result I'm looking for.
Any tips?
EDIT Using the suggestion from Larry, I was able to achieve what I wanted with the following
hon = Hash.new
hon['bob::params::search'] = Hash.new
hoh.each do |key,value|
value.each do |k, v|
hon['bob::params::search'][k] = hoh['bob::params::search_vol_grp'][k].merge! (hob['bob::params::search_q_broker'][k])
end
end
I also updated the 2nd hash to use a fixnum rather then a string as indicated by Darshan.
Thanks for all the pointers guys!
Upvotes: 0
Views: 122
Reputation: 34031
Giving your Hashes valid variable names, closing the Hashes, and making the second Hash use a Fixnum rather than a String for the top-level key, this appears to do what you want:
h1 = {2=>{"search_group_id"=>2, "vol_ids"=>"2,627,628", "num_shards"=>32,
"num_replicas"=>1}}
h2 = {2=>{"master_host"=>"hsrchq01p1", "master_port"=>"61616",
"slave_host"=>"hsrchq01p2", "slave_port"=>"61616"}}
h1.merge(h2){|key, first, second| first.merge(second)}
# => {2=>{"search_group_id"=>2, "vol_ids"=>"2,627,628", "num_shards"=>32,
# "num_replicas"=>1, "master_host"=>"hsrchq01p1", "master_port"=>"61616",
# "slave_host"=>"hsrchq01p2", "slave_port"=>"61616"}}
Upvotes: 1
Reputation: 3283
Something like this...
1[2].merge(2[2])
You need to merge the inner hashes.
Upvotes: 0