2013-02-22 151 views
1

我有以下的對象捕獲嵌套的哈希值(從Ominauth-Facebook)的所謂myAuth搜索鍵在Rails中嵌套散列

<Ominauth::AuthHash credentials 
        extra=#<Hashie:: Mash 
        raw_info=#<Hashie::Mash email="[email protected]">>> 

我想提取電子郵件,所以我用:

myAuth['extra']['raw_info']['email'] 

但是,我想搜索整個散列並獲得鍵email的值而不知道確切的散列結構。我應該怎麼做呢?

謝謝。

+1

[在包含任意數量的嵌套散列和數組的散列內深入查找鍵/值對]的可能重複(http://stackoverflow.com/questions/8301566/find-key-value-pairs-deep-inside -a-hash-containing-an-any-number-of-nested) – deefour 2013-02-22 19:27:55

+0

謝謝Deefour。我會投票結束這個。 – AdamNYC 2013-02-22 20:03:40

回答

4

不知道這是否是最好的解決辦法,但我會做到:如果該鍵存在或假

h = {seal: 5, test: 3, answer: { nested: "damn", something: { email: "yay!" } } } 

def search_hash(h, search) 
    return h[search] if h.fetch(search, false) 

    h.keys.each do |k| 
    answer = search_hash(h[k], search) if h[k].is_a? Hash 
    return answer if answer 
    end 

    false 
end 

puts search_hash(h, :email) 

這將返回值。