且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从嵌套散列中获取键或键的存在值?

更新时间:2022-10-18 18:19:02

  %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