有没有一种“简单”的方法,而不是手写 Hash#dig
执行的那种嵌套哈希/数组遍历,我可以确定一个键是否存在于一个深度嵌套的哈希?另一种询问方式是说“确定是否分配了任何值”。
没有分配任何内容的 Hash 与显式分配了 nil
之间是有区别的 - 特别是如果 Hash 是用与 nil
不同的缺失键默认值构造的>!
h = { :one => { :two => nil }}
h.dig(:one, :two).nil? # => true; but :two *is* present; it is assigned "nil".
h[:one].key?(:two) # => true, because the key exists
h = { :one => {}}
h.dig(:one, :two).nil? # => true; :two *is not* present; no value is assigned.
h[:one].key?(:two) # => FALSE, because the key does not exist
最佳答案
如果你纯粹是检查一个key是否存在,你可以结合使用dig
和key?
。在您的键系列中的最后一个或最后一个键上使用 key?
。
input_hash = {
hello: {
world: {
existing: nil,
}
}
}
# Used !! to make the result boolean
!!input_hash.dig(:hello, :world)&.key?(:existing) # => true
!!input_hash.dig(:hello, :world)&.key?(:not_existing) # => false
!!input_hash.dig(:hello, :universe)&.has_key?(:not_existing) # => false
关于ruby - (不是#dig!)如何确定深度嵌套的 Ruby 哈希中的键*存在*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66737620/