Skip to content

Instantly share code, notes, and snippets.

@ascot21
Created April 23, 2014 22:06
Show Gist options
  • Save ascot21/11234106 to your computer and use it in GitHub Desktop.
Save ascot21/11234106 to your computer and use it in GitHub Desktop.
Merge hashes while adding values of identical keys
a = [{'a' => 30, 'b' => 14}, {'a' => 4, 'b' => 23, 'c' => 7}, {'a' => 6, 'b' => 20, 'c' => 5}]
puts a.inject{|tot, new| tot.merge(new){|k,val_from_a,val_from_b|val_from_a+val_from_b}}
=> {"a"=>40, "b"=>57, "c"=>12}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment