title: Sum key value pairs of identical keys in nested Hash
body: <p>I have the following array of hashes -</p>
  
  <pre><code>array = [{:Air_Duct_Cleaning=&gt;{:impressions=&gt;92, :clicks=&gt;2, :conversions=&gt;0}, :Carpet_Cleaning=&gt;{:impressions=&gt;297, :clicks=&gt;0, :conversions=&gt;0}, :Brand_Terms=&gt;{:impressions=&gt;273, :clicks=&gt;9, :conversions=&gt;1}}, {:Brand_Terms=&gt;{:impressions=&gt;275, :clicks=&gt;3, :conversions=&gt;0}}, {:Air_Duct_Cleaning=&gt;{:impressions=&gt;51, :clicks=&gt;1, :conversions=&gt;0}, :Carpet_Cleaning=&gt;{:impressions=&gt;225, :clicks=&gt;0, :conversions=&gt;0}, :Brand_Terms=&gt;{:impressions=&gt;326, :clicks=&gt;12, :conversions=&gt;2}}]
  </code></pre>
  
  <p>I'm attempting to sum the key value pairs of identical keys.  For example - </p>
  
  <pre><code>air_duct = array.map {|m| m[:Air_Duct_Cleaning]}.compact
  =&gt; [{:impressions=&gt;92, :clicks=&gt;2, :conversions=&gt;0}, {:impressions=&gt;51, :clicks=&gt;1, :conversions=&gt;0}]
  
  air_duct_total = air_duct.inject{|x,y| x.merge(y){|a,b,c| b + c}}
  =&gt; {:impressions=&gt;143, :clicks=&gt;3, :conversions=&gt;0}
  </code></pre>
  
  <p>However, I need to do this without knowing the keys of the first level hash (won't know the key of <code>:Air_Duct_Cleaning</code>).  I was trying to iterate through the array running something like</p>
  
  <pre><code>key_groups = array.map {|m| m.map {|key, value| key}}
  </code></pre>
  
  <p>Hoping that would position each key in place of <code>:Air_Duct_Cleaning</code> and I'd get something like</p>
  
  <pre><code>[{:Air_Duct_Cleaning =&gt;{:impressions=&gt;92, :clicks=&gt;2, :conversions=&gt;0}, {:impressions=&gt;51, :clicks=&gt;1, :conversions=&gt;0}, {:Carpet_Cleaning =&gt; {:impressions=&gt;297, :clicks=&gt;0, :conversions=&gt;0}, {:impressions=&gt;225, :clicks=&gt;0, :conversions=&gt;0}, {:Brand_Terms =&gt; {:impressions=&gt;273, :clicks=&gt;9, :conversions=&gt;1}, {:impressions=&gt;275, :clicks=&gt;3, :conversions=&gt;0}, {:impressions=&gt;326, :clicks=&gt;12, :conversions=&gt;2}]
  </code></pre>
  
  <p>So I could then use something like</p>
  
  <pre><code>totals = key_groups.map {|m| m.inject{|x,y| x.merge(y){|a,b,c| b + c}}}
  </code></pre>
  
  <p>And ultimately end up with </p>
  
  <pre><code>[{:Air_Duct_Cleaning =&gt; {:impressions=&gt;143, :clicks=&gt;3, :conversions=&gt;0}, {:Carpet_Cleaning =&gt; {:impressions=&gt;522, :clicks=&gt;0, :conversions=&gt;0}, {:Brand_Terms =&gt; {:impressions=&gt;874, :clicks=&gt;24, :conversions=&gt;3}] 
  </code></pre>