"bob@bob.com", "Account" => { "Exchange"-6ren">
gpt4 book ai didi

arrays - 使用键数组遍历嵌套的 Ruby 哈希

转载 作者:数据小太阳 更新时间:2023-10-29 07:24:27 27 4
gpt4 key购买 nike

给定一个包含 n 层嵌套值的哈希值、一个字段名和一个路径

contact = {
"Email" => "bob@bob.com",
"Account" => {
"Exchange" => true,
"Gmail" => false,
"Team" => {
"Closing_Sales" => "Bob Troy",
"Record" => 1234
}
}
}

field = "Record"
path = ["Account", "Team"] #Must support arbitrary path length

如何定义一种方法来检索路径末尾的字段值。

def get_value(hash, field, path)
?
end

get_value(contact, "Record", ["Account", "Team"])
=> 1234

最佳答案

让我们将“字段”视为“路径”的最后一个元素。那就简单了

def grab_it(h, path)
h.dig(*path)
end

grab_it contact, ["Account", "Team", "Record"]
#=> 1234
grab_it contact, ["Account", "Team", "Rabbit"]
#=> nil
grab_it(contact, ["Account", "Team"]
# => {"Closing_Sales"=>"Bob Troy", "Record"=>1234}
grab_it contact, ["Account"]
#=> {"Exchange"=>true, "Gmail"=>false, "Team"=>{"Closing_Sales"=>"Bob Troy",
# "Record"=>1234}}

Hash#dig在 v2.3 中添加。

关于arrays - 使用键数组遍历嵌套的 Ruby 哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40689192/

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