1

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.

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
AdamNYC
  • 19,887
  • 29
  • 98
  • 154
  • 1
    possible duplicate of [Find key/value pairs deep inside a hash containing an arbitrary number of nested hashes and arrays](http://stackoverflow.com/questions/8301566/find-key-value-pairs-deep-inside-a-hash-containing-an-arbitrary-number-of-nested) – deefour Feb 22 '13 at 19:27
  • Thanks Deefour. I'll vote to close this. – AdamNYC Feb 22 '13 at 20:03

1 Answers1

4

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.

Kaeros
  • 1,138
  • 7
  • 7