ruby的新特性,在嵌套散列中查找值



我不知道如何从这个嵌套的哈希中获得@responseType的值。

{
  "mgmtResponse": {
    "@responseType": "operation"}}

虽然@tadman严格正确,但使用新的ruby 2.3 dig函数更安全。最大的区别是,如果键不存在,dig将返回nil,而括号表示法将抛出NoMethodError: undefined method `[]' for nil:NilClass。要使用dig,可以使用hash.dig("mgmtResponse", "@responseType")

您在问题中使用的哈希语法有点奇怪和尴尬,因为似乎键是字符串(因为它们被引号包围),但因为您使用:符号ruby将它们转换为符号。因此,在您的散列hash.dig(:mgmtResponse, :@responseType)将工作,hash.dig("mgmtResponse", "@responseType")将为nil,因为那些字符串键不存在。如果您使用=>符号而不是:符号,则hash.dig("mgmtResponse", "@responseType")将存在,hash.dig(:mgmtResponse, :@responseType)将是nil

所以你要找的是这个:

hash = {
  "mgmtResponse" => {
    "@responseType" => "operation"
  }
}
hash.dig("mgmtResponse", "@responseType") #=> "operation"

或者如果你想使用你的(令人困惑的)哈希语法,那么:

hash = {
  "mgmtResponse": {
    "@responseType": "operation"
  }
}
hash.dig(:mgmtResponse, :@responseType) #=> "operation"

直接向上遍历:

hash['mgmtResponse']['@responseType']

您可以使用[]方法来处理数组,散列,甚至字符串:

"test"[2]
# => "s"

最新更新