Skip to content

Instantly share code, notes, and snippets.

@cwoodcox
Created August 11, 2011 19:40
Show Gist options
  • Save cwoodcox/1140557 to your computer and use it in GitHub Desktop.
Save cwoodcox/1140557 to your computer and use it in GitHub Desktop.
Array of Hashes Totaling
array = [{:stat1 => 34, :stat2 => 37}, {:stat1 => 45, :stat2 => 78}]
total = {}
array.each do |element|
element.each do |key, val|
total[key] ||= 0
total[key] += val
end
end
total
# => { :stat1 => 79, :stat2 => 115 }
array = [{:stat1 => 34, :stat2 => 37}, {:stat1 => 45, :stat2 => 78}]
total = {}
array = [{:stat1 => 34, :stat2 => 37}, {:stat1 => 45, :stat2 => 78}]
array.reduce({}) do |total, element|
pairs.each do |key, val|
total[key] ||= 0
total[key] += val
end
total
end
@anewusername1
Copy link

array.reduce({}) {|h,pairs| pairs.each {|k,v| h[k] ||= 0; h[k] += v};h}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment