ruby - (不是#dig!)如何确定深度嵌套的 Ruby 哈希中的键*存在*?

标签 ruby ruby-hash

有没有一种“简单”的方法,而不是手写 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是否存在,你可以结合使用digkey?。在您的键系列中的最后一个或最后一个键上使用 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/

相关文章:

javascript - Rails 应用程序中搜索框的自动过滤

ruby-on-rails - 如何从 JSON 响应中提取召唤师名称?

ruby - 你如何模拟 RSpec 中的 break 语句?

java - 从静态类型到动态类型

ruby - Rails - ActiveAdmin 未在菜单中显示新资源

ruby - 将散列值搜索到另一个散列中并创建具有匹配值的新散列

ruby - 是什么启发了 Ruby 的 =begin .. =end 注释 block 语法?

ruby - 切片 vs 提取!轨道 5

ruby - Ruby 中的 "append-only"/"write-only"散列