2013-06-05 130 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 
相關問題