如何从嵌套哈希中获取密钥的值或密钥的存在?
例如:
a = { "a"=> { "b" => 1, "c" => { "d" => 2, "e" => { "f" => 3 } }}, "g" => 4}
有没有直接的方法来获取“f”的值?或者有一种方法可以知道嵌套哈希中是否存在密钥?
答案 0 :(得分:5)
%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"
或者,为了避免错误:
%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
答案 1 :(得分:2)
def is_key_present?(hash, key)
return true if hash.has_key?(key)
hash.each do |k, v|
return true if v.kind_of?(Hash) and is_key_present?(v, key)
end
false
end
> is_key_present?(a, 'f')
=> true