Ruby hash.dig 使用数组作为参数?

Ruby hash.dig using array as argument?

我有一个嵌套的数据散列

foo => {
  'user' => { 
    'address' => {
      'street' => '1234'
    }
  }
}

我可以使用 Hash.dig

访问这些值
foo.dig('user', 'address', 'street')
1234

当值是可变的并且在数组中定义时,您将如何使用 hash.dig?

query=["users", "address", "street"]
  
foo.dig(query) # <= doesn't work  
foo.dig(query.to_s) # <= doesn't work  

查看 ruby 文档,Hash.dig 似乎采用多个参数,但不采用数组

https://ruby-doc.org/core-2.3.0_preview1/Hash.html#method-i-dig

您可以使用 splat 运算符将数组拆分为参数列表,方法如下:

foo.dig(*query)

对于典型的 use-case,我会使用 Alex 的回答,但由于它将数组分解为参数,因此开销更大,并且输入量大,我得到了堆栈太深的错误。这不是您将面临的错误,除非您有大量清单,但无论如何都值得理解。

# one million keys
# note that none of these are actually present in the hash
query = 1.upto(1_000_000).to_a

foo.dig(*query)
# => StackTooDeep

query.reduce(foo) do |memo, key|
  memo&.dig(key) || break
end
# => returns nil instantly