1, "b" => 2, "c" => 3 } hash2 = {"a" => 1, "b" => 2-6ren">
gpt4 book ai didi

Ruby - 将两个散列与一些类似的键合并

转载 作者:行者123 更新时间:2023-12-02 01:27:53 25 4
gpt4 key购买 nike

本质上我只想合并两个哈希中出现的键。最终目标是增加或乘以这些值。

hash1 = {"a" => 1, "b" => 2, "c" => 3 }
hash2 = {"a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5}
{"a" => 2, "b" => 4, "c" => 6 }

这在某种意义上添加了正确的值,但也返回了 d 和 e。

hash1.merge(hash2) { |key1, value1, value2| value1 + value2 }
#=> {"a" => 2, "b" => 4, "c" => 6, "d" => 4, "e" => 5}

最佳答案

尝试下面的代码

hash1 = {"a" => 1, "b" => 2, "c" => 3 }
hash2 = {"a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5}


(hash1.keys & hash2.keys).map{ |key| [key, hash1[key] + hash2[key]]}.to_h
=> {"a"=>2, "b"=>4, "c"=>6}

关于Ruby - 将两个散列与一些类似的键合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74012975/

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