Search code examples
rubyhash-of-hashes

Merge values of 2 hashes into 1 using Ruby


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!


Solution

  • Something like this...

    1[2].merge(2[2])
    

    You need to merge the inner hashes.