Skip to content

Instantly share code, notes, and snippets.

@PatrickTulskie
Created October 22, 2009 16:03
Show Gist options
  • Save PatrickTulskie/216050 to your computer and use it in GitHub Desktop.
Save PatrickTulskie/216050 to your computer and use it in GitHub Desktop.
Used to total an array of hashes that have similar keys
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