title: Traversing a Hash Recursively in Ruby
body: <p>I'm having a problem with this function that traverses a Hash. The Hash may contain an Array of Hashes. I want the method to search for an id and then return just the nested hash it finds. </p>
  
  <p>It seems to work for the traversal, but it returns the original value passed in.</p>
  
  <pre><code>require 'rubygems'
  require 'ruby-debug'
  
  def find_by_id(node, find_this="")
    if node.is_a?(Hash)
      node.each do |k,v|
        if v.is_a?(Array)
          v.each do |elm|
            if elm["_id"] == find_this &amp;&amp; !find_this.empty?
              return elm      # THIS IS WHAT I WANT!
            else
              find_by_id(elm, find_this)
            end
          end
        end
      end
    end
  end
  
  x = {"name" =&gt; "first", "_id"=&gt;'4c96a9a56f831b0eb9000005', "items"=&gt;["name" =&gt; "second", "_id"=&gt;'4c96a9af6f831b0eb9000009', "others"=&gt;[{"name" =&gt; "third", "_id"=&gt;'4c96a9af6f831b0eb9000007'}, {"name" =&gt; "fourth", "_id"=&gt;'4c96a9af6f831b0eb9000008'}] ] }
  
  find_by_id(x, '4c96a9af6f831b0eb9000008')
  </code></pre>