如何从嵌套散列中获取键或键的存在值? [英] How to get value of key or key presence from nested hash?
本文介绍了如何从嵌套散列中获取键或键的存在值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:
$ b $
a = {a=> {b=> 1,c=> {d=> 2,e=> {f=> 3}}},g=> 4}
有没有直接的方法来获得f的值?或者有没有一种方法可以知道嵌套散列中键的存在?
解决方案
%w [acef] .inject(a,&:fetch)#=> 3
%w [a c e x] .inject(a,&:fetch)#>找不到错误键:x
%w [x] .inject(a,&:fetch)#=>找不到错误键:x
或者,为避免错误: $ b $ (a,&:fetch)rescueKey not found#=> b
%w [acef] .inject (a,&:fetch)rescue找不到密钥#=>未找到密钥
%w [x] .inject(a,&:fetch)rescueKey not found#=>未找到密钥
How do I get the value of a key or the key's presence from a nested hash?
For example:
a = { "a"=> { "b" => 1, "c" => { "d" => 2, "e" => { "f" => 3 } }}, "g" => 4}
Is there any direct method to get the value of "f"? Or is there a method to know the presence of key in the nested hash?
解决方案
%w[a c e f].inject(a, &:fetch) # => 3
%w[a c e x].inject(a, &:fetch) # > Error key not found: "x"
%w[x].inject(a, &:fetch) # => Error key not found: "x"
Or, to avoid errors:
%w[a c e f].inject(a, &:fetch) rescue "Key not found" # => 3
%w[a c e x].inject(a, &:fetch) rescue "Key not found" # => Key not found
%w[x].inject(a, &:fetch) rescue "Key not found" # => Key not found
这篇关于如何从嵌套散列中获取键或键的存在值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文