合并两个哈希值

时间:2017-07-20 16:53:53

标签: ruby hash

我有2个带键和值的哈希

h1 = {"January"=>1, "February"=>2, "March"=>4, "April"=>5, "May"=>5, "June"=>6}

h2 = {1=>3, 2=>5, 3=>10, 4=>12, 6=>14}

我期待得到像

这样的结果
result = {3=>1, 5=>2, 10=>4, 12=>5, 14=>6}

我试过这个解决方案

  

如果你想要1回复"首先"和"一个",你需要存储   它们在一个数组中,然后是1映射到的数值。

results = {}

  hash1.each do |key, value|   if results[key].nil?
     results[key] = [value]   else
     results[key] << value

hash2.each do |key, value|   if results[key].nil?
     results[key] = [value]   else
     results[key] << value

results[1]
# => ["one", "first"]

但我的结果是

{1=>[3], 2=>[5], 3=>[10], 4=>[12], 6=>[14], "January"=>[1], "February"=>[2], "March"=>[4], "April"=>[5], "May"=>[5], "June"=>[6]}

1 个答案:

答案 0 :(得分:1)

这是因为你把它放在一个列表中,尝试做跟随,不需要做第二个foreach循环:

  

推荐方式:

hash1 = {"January"=>1, "February"=>2, "March"=>4, "April"=>5, "May"=>5, "June"=>6}

hash2 = {1=>3, 2=>5, 3=>10, 4=>12, 6=>14}

results = {}

#here you have to swap key-value for value-key

hash2.each do |value, key| 
  if results[key].nil?
    results[key] = value
  else 
    results[key] << value
  end
end

results
  

=&GT; {3 =&gt; 1,5 =&gt; 2,10 =&gt; 3,12 =&gt; 4,14 =&gt; 6}

     

替代方式:

您可以压缩两个列表,一个键,另一个值,然后将它们放在字典中:

hash1 = {"January"=>1, "February"=>2, "March"=>4, "April"=>5, "May"=>5, "June"=>6}

hash2 = {1=>3, 2=>5, 3=>10, 4=>12, 6=>14}

results = {}

(hash2.values).zip(hash1.values).each do |key, value| 
  if results[key].nil?
    results[key] = value
  else 
    results[key] << value
  end
end

results
  

=&GT; {3 =&gt; 1,5 =&gt; 2,10 =&gt; 4,12 =&gt; 5,14 =&gt; 5}