gpt4 book ai didi

ruby-on-rails - 有人可以解释一下 Hash#dig 与 Hash#fetch 之间的区别是什么

转载 作者:行者123 更新时间:2023-12-04 14:32:08 27 4
gpt4 key购买 nike

我正在尝试获取哈希中的嵌套值。我试过使用 Hash#fetchHash#dig但我不明白它们应该如何组合。

我的哈希如下。

response = {
"results":[
{
"type":"product_group",
"value":{
"destination":"Rome"
}
},
{
"type":"product_group",
"value":{
"destination":"Paris"
}
},
{
"type":"product_group",
"value":{
"destination":"Madrid"
}
}
]
}

我试过以下
response.dig(:results)[0].dig(:value).dig(:destination) #=> nil
response.dig(:results)[0].dig(:value).fetch('destination') #=> Rome

所需的返回值是 "Rome" .第二个表达式有效,但我想知道它是否可以简化。

我使用 Ruby v2.5 和 Rails v5.2.1.1。

最佳答案

Hash#fetch在这里不相关。那是因为fetchHash#[] 相同当,如这里,fetch只有一个参数。所以让我们专注于dig .

一家三口dig Ruby v2.3 中引入了方法:Hash#dig , Array#digOpenStruct#dig .关于这些方法的一个有趣的事情是它们相互调用(但在文档中没有解释,甚至在示例中也没有解释)。在你的问题中,我们可以写:

response.dig(:results, 0, :value, :destination)
#=> "Rome"
response是一个哈希所以 Hash#dig评估 response[:results] .如果它的值为 nil然后表达式返回 nil .例如,
response.dig(:cat, 0, :value, :destination)
#=> nil

事实上, response[:results]是一个数组:
arr = response[:results]
#=> [{:type=>"product_group", :value=>{:destination=>"Rome"}},
# {:type=>"product_group", :value=>{:destination=>"Paris"}},
# {:type=>"product_group", :value=>{:destination=>"Madrid"}}]
Hash#dig因此调用 Array#digarr , 获取哈希
h = arr.dig(0)
#=> {:type=>"product_group", :value=>{:destination=>"Rome"}}
Array#dig然后调用 Hash#digh :
g = h.dig(:value)
#=> {:destination=>"Rome"}

最后, g作为一个散列, Hash#dig调用 Hash#digg :
g.dig(:destination)
#=> "Rome"

关于ruby-on-rails - 有人可以解释一下 Hash#dig 与 Hash#fetch 之间的区别是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55429632/

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