title: Ruby hash of hash initialization
body: <p>Consider @data is an array of ActiveRecords with fields <em>date</em>, <em>class</em>, <em>name</em>, and <em>grade</em>.  Assuming I want to end up with two hashes, one being a unique set of all the dates per name; the other broken down by class, then date, then name to reveal the grade.</p>
  
  <pre><code>dates  = {}
  grades = {}
  
  @data.each do |d|
     dates[ d.name ][ d.date ] = ''                              # 1
     grades[ d.class =&gt; { d.date =&gt; { d.name =&gt; d.grade } } ]    # 2 
  end
  </code></pre>
  
  <ol>
  <li><p>results in an error:</p>
  
  <blockquote>
    <p>undefined method `[]=' for nil:NilClass  </p>
  </blockquote>
  
  <p><code>dates[ d.name =&gt; { d.date =&gt; '' } ]</code> only stores the last record (does not merge into the older results)</p></li>
  <li><p>doesn't error, but ends with an empty hash <code>{}</code></p></li>
  </ol>
  
  <p>After getting back into Perl, I've forgotten how to initialize and add to a hash of hashes in Ruby.</p>
  
  <hr>
  
  <h3>Update</h3>
  
  <p>For the first one (<em>dates</em>), it looks like I can do the following inside the loop:</p>
  
  <pre><code>dates[ d.name ] ||= { d.date =&gt; '' }
  dates[ d.name ][ d.date ] = ''
  </code></pre>
  
  <p>Looking at the docs, I don't know if this is the proper way to do it, it also seems inefficient, since it will be doing the assignment twice for the first value.  It also would suggest that for each key, I need to declare/initialize the underlying data structure, which would get lengthy the deeper the hash of hashes gets (like the <em>grades</em> hash).</p>
  
  <hr>
  
  <p>Source: </p>
  
  <pre><code>[{ name: 'greg', class:'science', date:'jan', grade:'a' },
   { name: 'greg', class:'math'   , date:'jan', grade:'b' },
   { name: 'barb', class:'history', date:'jan', grade:'a' },
   { name: 'barb', class:'science', date:'feb', grade:'c' }]
  </code></pre>
  
  <p><em>dates</em> would look something like:</p>
  
  <pre><code>{ 'greg' =&gt; { 'jan' =&gt; '' },
    'barb' =&gt; { 'jan' =&gt; '' ,
                'feb' =&gt; '' 
              }
  }
  </code></pre>
  
  <p><em>grades</em> would look something like:</p>
  
  <pre><code>{ 'science' =&gt; { 'jan' =&gt; { 'greg' =&gt; 'a' } ,
                   'feb' =&gt; { 'barb' =&gt; 'c' } },
    'math'    =&gt; { 'jan' =&gt; { 'greg' =&gt; 'b' } },
    'history' =&gt; { 'jan' =&gt; { 'barb' =&gt; 'a' } }
  }
  </code></pre>