2016-11-11 65 views
-1

我无法弄清楚如何从这个嵌套散列获取@responseType的值。ruby​​新手,在嵌套散列中查找值

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

如果'h'是你的哈希,'g^= h [:mgmtResponse]#=> {:@responseType =>“operation”}',所以你需要'g [:@ responseType]#=>“operation”',这与'h [:mgmtResponse] [:@responseType]'。顺便提一下,在例子中为每个输入分配一个变量是有帮助的(例如,'h = {“mgmtResponse”:{“@responseType”:“operation”}}')。这样读者可以在回答和评论中引用这些变量,而无需定义它们。 –

回答

1

直线上升遍历:

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

可以使用[]办法数组,哈希,甚至字符串:

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

虽然@tadman是完全正确,它的安全使用新的红宝石2.3挖功能。最大的区别是,如果该键不存在,dig将返回nil,而括号表示会抛出NoMethodError: undefined method `[]' for nil:NilClass。要使用dig,您可以使用hash.dig("mgmtResponse", "@responseType")

您在问题中使用的散列语法有点奇怪且很尴尬,因为看起来键是字符串(因为它们被引号括起来),但是因为您使用了:表示法,所以ruby将它们转换为符号。所以你的散列hash.dig(:mgmtResponse, :@responseType)将工作,hash.dig("mgmtResponse", "@responseType")将为零,因为那些字符串键不存在。如果使用=>表示法而不是:表示法,则将存在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" 
+0

'hash.dig(“mgmtResponse”,“@responseType”)#=>无'当我尝试? –

+2

使用'{“key”:“value}'将密钥转换为符号!这就是为什么! – thesecretmaster

+0

好的一个好的,让它工作。 –