new to ruby, finding a value in a nested hash -


i can't figure out how value of @responsetype nested hash.

{   "mgmtresponse": {     "@responsetype": "operation"}} 

while @tadman strictly correct, it's safer use new ruby 2.3 dig function. big difference if key doesn't exist, dig return nil, whereas brackets notation throw nomethoderror: undefined method `[]' nil:nilclass. use dig, use hash.dig("mgmtresponse", "@responsetype").

the syntax hash used in question little strange , awkward in appears keys strings (because surrounded in quotes) because use : notation ruby converts them symbols. on hash hash.dig(:mgmtresponse, :@responsetype) work , hash.dig("mgmtresponse", "@responsetype") nil, because string keys not exist. if use => notation instead of : notation, hash.dig("mgmtresponse", "@responsetype") exists , hash.dig(:mgmtresponse, :@responsetype) nil.

so looking this:

hash = {   "mgmtresponse" => {     "@responsetype" => "operation"   } }  hash.dig("mgmtresponse", "@responsetype") #=> "operation" 

or if want use (confusing) hash syntax then:

hash = {   "mgmtresponse": {     "@responsetype": "operation"   } }  hash.dig(:mgmtresponse, :@responsetype) #=> "operation" 

Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -