10, "b" => 20, "c"=>34, "d"=>3} h2 = { "a" => 11, "b" => 21, -6ren">
gpt4 book ai didi

ruby - 将两个散列与一个公共(public) key 结合起来

转载 作者:数据小太阳 更新时间:2023-10-29 08:23:09 26 4
gpt4 key购买 nike

我一直在尝试在 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 的新手,所以我想我在这里遗漏了一些非常基本的东西。我将不胜感激任何帮助。

最佳答案

关于:

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

关于ruby - 将两个散列与一个公共(public) key 结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21573316/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com