没有重复的哈希连接/合并并选择最大键值?
h1 = {"a"=> "121","b"=> "248","d"=> "192","e"=> "182"}
h2 = {"a"=> "458","b"=> "122","c"=> "562","f"=> "224","g"=> "352"}
这是我的输入我尝试合并它但我只有这个输出
merge_hash = {"a"=>"121", "b"=>"248", "c"=>"562", "f"=>"224", "g"=>"352", "d"=>"192", "e"=>"182"}
但我想要这个
merge_hash = {"a"=>"458", "b"=>"248", "c"=>"562", "f"=>"224", "g"=>"352", "d"=>"192", "e"=>"182"}
我用它来合并哈希 merge_hash = h2.merge(h1) 任何人请帮我解决这个问题
回答
似乎您想在有重叠时选择最大值。为此,您可以使用以下块形式merge
:
h1.merge(h2) do |key, old_val, new_val|
[old_val, new_val].max
end
此块仅在存在重叠时运行,其返回值决定使用哪个值
- `h1.merge(h2) { |_key, *values| values.max }` is a nice application for the splat operator.