2013-06-05 129 views
1

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

例如:

a = { "a"=> { "b" => 1, "c" => { "d" => 2, "e" => { "f" => 3 } }}, "g" => 4} 

是否有任何直接的方法来获得 “F” 的值?或者有没有一种方法来知道嵌套散列中键的存在?

+0

看一看[这里](http://stackoverflow.com/questions/3748744/traversing-a-hash-recursively-in -ruby)进行一些递归散列工作。 – CharlesJHardy

+0

你可以看看这里 - http://metaskills.net/2012/03/12/store-configurable-a-lesson-in-recursion-in-ruby/ –

+0

可能的重复[Ruby风格:如何检查是否一个嵌套的哈希元素存在](http://stackoverflow.com/questions/1820451/ruby-style-how-to-check-whether-a-nested-hash-element-exists) – mysmallidea

回答

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 
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 
相关问题