title: Sum ruby hash values
body: <p>I am trying to sum values from a ruby hash but using either inject or reduce does not return the correct answer. It seems as though these methods are overwriting the current value being stored instead of summing them.</p>
  
  <p>My hash look like this:</p>
  
  <pre><code>@test = [
    {"total"=&gt;18, "type"=&gt;"buy", "date"=&gt;Thu, 21 Nov 2013, "instrument_code"=&gt;"food"},
    {"total"=&gt;92, "type"=&gt;"buy", "date"=&gt;Thu, 14 Nov 2013, "instrument_code"=&gt;"food"},
    {"total"=&gt;12, "type"=&gt;"buy", "date"=&gt;Wed, 20 Nov 2013, "instrument_code"=&gt;"drink"},
    {"total"=&gt;1, "type"=&gt;"buy", "date"=&gt;Mon, 11 Nov 2013, "instrument_code"=&gt;"food"}
  ]
  </code></pre>
  
  <p>Here is my inject code that fails:</p>
  
  <pre><code>def additions_per_security
    @test.group_by { |i| i.type }.each do |key, value|
      if key == "buy"
        value.group_by{ |i| i.date }.each do |key, value|
          @sortable_additions[key] = value
        end
        @sorted_additions = @sortable_additions.sort_by { |key,value| key }
        @sorted_additions.shift
        @additions_per_security = Hash[@sorted_additions.map { |key, value| 
         [key, value]
        }]
        @additions_per_security.each do |key, value|
          value.group_by { |i| i.instrument_code }.each do |key, value|
            @additions_security[key] = value.inject(0){ |result, transaction| 
              (result += transaction.total)
            }
          end
        end
      end
    end
    return @additions_security
  end
  </code></pre>
  
  <p>Here is my reduce code that fails:</p>
  
  <pre><code>def additions_per_security
    @@test.group_by { |i| i.type }.each do |key, value|
      if key == "buy"
        value.group_by { |i| i.date }.each do |key, value|
          @sortable_additions[key] = value
        end
        @sorted_additions = @sortable_additions.sort_by { |key,value| key }
        @sorted_additions.shift
        @additions_per_security = Hash[@sorted_additions.map { |key, value| 
          [key, value]
        }]
        @additions_per_security.each do |key, value|
          value.group_by { |i| i.instrument_code }.each do |key, value|
            @additions_security[key] = value.map { |p| p.total }.reduce(0,:+)
          end
        end
      end
    end
    return @additions_security
  end
  </code></pre>
  
  <p>I have a hash and I want to sum the totals for all keys except the first date.</p>
  
  <p>I am currently getting the following:</p>
  
  <pre><code>{"drink"=&gt;12.0, "food"=&gt;92}
  </code></pre>
  
  <p>My expected result will look like this:</p>
  
  <pre><code>{"drink"=&gt;12.0, "food"=&gt;110}
  </code></pre>
  
  <p>Thanks in advance for any advice.</p>