{:speed => "100mph"}} 得到: {:car => {:color => "red",-6ren">
gpt4 book ai didi

ruby - 如何合并 Ruby 哈希

转载 作者:数据小太阳 更新时间:2023-10-29 06:21:44 25 4
gpt4 key购买 nike

如何合并这两个哈希:

{:car => {:color => "red"}}
{:car => {:speed => "100mph"}}

得到:

{:car => {:color => "red", :speed => "100mph"}}

最佳答案

有一个Hash#merge方法:

ruby-1.9.2 > a = {:car => {:color => "red"}}
=> {:car=>{:color=>"red"}}
ruby-1.9.2 > b = {:car => {:speed => "100mph"}}
=> {:car=>{:speed=>"100mph"}}
ruby-1.9.2 > a.merge(b) {|key, a_val, b_val| a_val.merge b_val }
=> {:car=>{:color=>"red", :speed=>"100mph"}}

如果你需要合并嵌套的哈希,你可以创建一个递归方法:

def merge_recursively(a, b)
a.merge(b) {|key, a_item, b_item| merge_recursively(a_item, b_item) }
end

ruby-1.9.2 > merge_recursively(a,b)
=> {:car=>{:color=>"red", :speed=>"100mph"}}

关于ruby - 如何合并 Ruby 哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8415240/

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