Created
October 22, 2009 16:03
-
-
Save PatrickTulskie/216050 to your computer and use it in GitHub Desktop.
Used to total an array of hashes that have similar keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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