2016-11-11 62 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

好的一個好的,讓它工作。 –