title: Ruby - efficiently storing data in deeply nested Hash?
body: <p>I'm writing a script the stores db info in a hash to be later available for easy access. My code looks something like this:</p>
  
  <pre><code>my_hash = {}
  
  connection.query("select * from ...").each_hash do |row|
    date = row['date']
    ip   = row['ip']
    port = row['port']
    resp = row['avg_resp_time'].to_i
  
    unless my_hash.key?(ip)
      my_hash[ip] = { date =&gt; { port =&gt; resp } }
    else
      unless my_hash[ip].key?(date)
        my_hash[ip][date] = { port =&gt; resp }
      else
        unless my_hash[ip][date].key?(port)
          my_hash[ip][date][port] = resp 
        end
      end
    end
  end
  </code></pre>
  
  <p>This is just a sample, but the actual hash is nested sometimes 5-6 levels deep, and takes a long time to build for a large result set. I realize there's a tradeoff here between time-to-build-map / time-to-access-data, but I was wondering if there's a more efficient way to store data to be just as easily accessed in code, or a way to make my current script a bit more efficient - this hash building loop is my bottleneck at the moment. thanks.</p>