Module: HashRollup
- Defined in:
- lib/hash_rollup.rb
Overview
HashRollup
- Author
-
Joel Parker Henderson, [email protected]
- Copyright
-
Copyright © 2007-2009 Joel Parker Henderson
- License
-
CreativeCommons License, Non-commercial Share Alike
- License
-
LGPL, GNU Lesser General Public License
HashRollup aggregates value for a hash of hashes, for example to help calculate subtotals grouped by key.
Example:
h=Hash.new
h['a']=Hash.new
h['b']=Hash.new
h['c']=Hash.new
h['a']['x']=1
h['a']['y']=2
h['a']['z']=3
h['b']['x']=4
h['b']['y']=5
h['b']['z']=6
h['c']['x']=7
h['c']['y']=8
h['c']['z']=9
h.rollup => {"a"=>[1,2,3],"b"=>[4,5,6],"c"=>[7,8,9]}
Calculating subtotals
The rollup and rolldown methods can be useful for calculating subtotals by key.
Example:
h = h.rollup
r['a'].sum => 6
r['b'].sum => 15
r['c'].sum => 24
Instance Method Summary collapse
Instance Method Details
#rollup ⇒ Object
42 43 44 45 46 |
# File 'lib/hash_rollup.rb', line 42 def rollup a=self.class.new keys.each{|k| a[k]=self[k].values} a end |