如何从嵌套哈希获得密钥或密钥存在的价值?
如何从嵌套哈希中获取密钥的值或密钥的存在?
例如:
a = { "a"=> { "b" => 1, "c" => { "d" => 2, "e" => { "f" => 3 } }}, "g" => 4}
有没有直接的方法来获得“f”的值? 或者是否有一种方法可以知道嵌套哈希中是否存在密钥?
%w[acef].inject(a, &:fetch) # => 3 %w[acex].inject(a, &:fetch) # > Error key not found: "x" %w[x].inject(a, &:fetch) # => Error key not found: "x"
或者,为了避免错误:
%w[acef].inject(a, &:fetch) rescue "Key not found" # => 3 %w[acex].inject(a, &:fetch) rescue "Key not found" # => Key not found %w[x].inject(a, &:fetch) rescue "Key not found" # => Key not found
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