search for key in a nested hash in Rails

2019-07-30 14:14发布

问题:

I have the following nested hash (from Ominauth-Facebook) captured in an object called myAuth

<Ominauth::AuthHash credentials 
                     extra=#<Hashie:: Mash 
                     raw_info=#<Hashie::Mash email="myemail@gmail.com">>>

I would like to extract email, so I use:

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

However, I would like to search the entire hash and get the value for key email without knowing exact hash structure. How should I go about it?

Thank you.

回答1:

Don't know if this is the best solution, but i would do:

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)

This will return the value if the key exists or false.