0

我有 2 个哈希值,我需要使用 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"}}

我想结束的是以下内容 -

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}}

我已经尝试过使用合并和合并的各种尝试!但没有一个产生我正在寻找的最终结果。

有小费吗?

编辑 使用拉里的建议,我能够通过以下方式实现我想要的

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

我还更新了第二个哈希以使用固定数字,而不是 Darshan 指示的字符串。

感谢所有的指点家伙!

4

2 回答 2

1

为您的 Hashes 提供有效的变量名称,关闭 Hashes,并使第二个 Hash 使用 Fixnum 而不是 String 作为顶级键,这似乎可以满足您的要求:

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"}}
于 2013-05-13T23:23:19.987 回答
0

像这样的东西...

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

您需要合并内部哈希。

于 2013-05-13T22:54:35.863 回答