Skip to content

Instantly share code, notes, and snippets.

@bordy
Forked from PatrickTulskie/array_of_hashes_total.rb
Created October 22, 2009 16:57
Show Gist options
  • Save bordy/216082 to your computer and use it in GitHub Desktop.
Save bordy/216082 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'money'
require 'yaml'
class Array
def total_hashes
self.inject({}) do |totals, hsh|
hsh.each { |key, value| (totals[key] = totals[key] ? value + totals[key] : value) unless %w(String Hash Array).include?(value.class.to_s) } if hsh.is_a?(Hash)
totals
end
end
end
test_array = [
{ :fives => 5, :elevens => 'NA', :twenties => 'NA' },
{ :fives => 'NA', :elevens => 11.0, :twenties => 20 },
{ :fives => 5, :elevens => 11.0, :twenties => 20 },
{ :fives => 5, :elevens => 11.0, :twenties => 20, :funk => 12345 },
{ :fives => 5, :elevens => 11.0, :twenties => 20 },
{ :cash => Money.new(500, 'USD') },
{ :cash => Money.new(500, 'USD') },
{ :cash => Money.new(500, 'USD') }
]
puts test_array.total_hashes.to_yaml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment