我一直在尝试在Ruby中组合两个哈希。例如:
h1 = { "a" => 10, "b" => 20, "c"=>34, "d"=>3}
h2 = { "a" => 11, "b" => 21, "d"=>15}
我想要的输出是:
h{"a"=> 10, 11, "b"=>20,21, "c"=> 34, "d"=>3,15}
每个哈希都有相同的密钥,除了第二个哈希可能缺少一些。我想这两个值然后用相同的键表示。
这是我不成功的代码:
h1 = { "a" => 10, "b" => 20, "c"=>34, "d"=>3}
h2 = { "a" => 11, "b" => 21, "d"=>15}
h3= h1.update(h2){|key1, key2, val1, val2 |key1,h2_val=h2}
它给出了:
{"a"=>{"a"=>11, "b"=>21, "d"=>15}, "b"=>{"a"=>11, "b"=>21, "d"=>15}, "c"=>34, "d"=>{"a"=>11, "b"=>21, "d"=>15}}
我刚认识Ruby,所以我想我在这里缺少一些非常基本的东西。我将不胜感激任何帮助。
答案 0 :(得分:5)
怎么样:
h1 = { "a" => 10, "b" => 20, "c"=>34, "d"=>3}
h2 = { "a" => 11, "b" => 21, "d"=>15}
p h1.merge(h2){|key, old, new| Array(old).push(new) } #=> {"a"=>[10, 11], "b"=>[20, 21], "c"=>34, "d"=>[3, 15]}
这就是我如何编写它来组合2个以上的哈希:
h1 = { "a" => 10, "b" => 20, "c"=>34, "d"=>3}
h2 = { "a" => 11, "b" => 21, "d"=>15}
h3 = { "a" => 11, "b" => 21, "c"=> 1, "d"=>15}
merge_to_array = -> x,y { x.merge(y){|key, old, new| Array(old).push(new)} }
p [h1,h2,h3].reduce &merge_to_array #=> {"a"=>[10, 11, 11], "b"=>[20, 21, 21], "c"=>[34, 1], "d"=>[3, 15, 15]}
答案 1 :(得分:2)
h1 = { "a" => 10, "b" => 20, "c"=>34, "d"=>3}
h2 = { "a" => 11, "b" => 21, "d"=>15}
arr= []
arr << h1 << h2
data= arr.map(&:to_a).flatten(1).reduce({}) {|h,(k,v)| (h[k] ||= []) << v; h}
它给出了
{"a"=>[10, 11], "b"=>[20, 21], "c"=>[34], "d"=>[3, 15]}
答案 2 :(得分:0)
例如,使用#reduce
:
h1 = { "a" => 10, "b" => 20, "c"=>34, "d"=>3}
h2 = { "a" => 11, "b" => 21, "d"=>15}
h2.reduce(h1.dup) {|h,(k,v)| h[k] = (h[k] && [h[k], v] || v); h}
# => {"a"=>[10, 11], "b"=>[20, 21], "c"=>34, "d"=>[3, 15]}
答案 3 :(得分:0)
你要找的是什么并不完全清楚,因为你的示例输出是无效的,但这就是我要做的就是合并两个哈希而不踩键:
h1 = { "a" => 10, "b" => 20, "c"=>34, "d"=>3}
h2 = { "a" => 11, "b" => 21, "d"=>15}
new_hash = Hash.new{ |h, k| h[k] = [] }
[*h1, *h2].each { |k, v| new_hash[k] << v }
结果是:
new_hash # => {"a"=>[10, 11], "b"=>[20, 21], "c"=>[34], "d"=>[3, 15]}