Forks

Revisions

gist: 216050 Download_button fork
public
Description:
Used to total an array of hashes that have similar keys
Public Clone URL: git://gist.github.com/216050.git
Embed All Files: show embed
array_of_hashes_total.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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