# Re: better way to accumulate totals

**URL:** <https://www.ruby-forum.com/t/re-better-way-to-accumulate-totals/118798>\
**Category:** Ruby\
**Created:** [October 31, 2007, 1:21am UTC](https://www.ruby-forum.com/t/re-better-way-to-accumulate-totals/118798 "2007-10-31T01:21:23Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![robkuz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/34f0e0/32.png) [@robkuz](https://www.ruby-forum.com/u/robkuz)\
**Post date:** [October 31, 2007, 1:21am UTC](https://www.ruby-forum.com/t/re-better-way-to-accumulate-totals/118798/1 "2007-10-31T01:21:23Z")

</div>

Thank you for the very clear and helpful explanation!

* * *

Robert K.  
removed\_email\_address@domain.invalid

----- Original Message ----  
From: 7stud – [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
To: ruby-talk ML [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
Sent: Tuesday, October 30, 2007 5:20:12 PM  
Subject: Re: better way to accumulate totals

Robert K. wrote:

> ```
> when "Logical reads:"
> 
> $log_read_cnt[0] += 1
> $log_read_cnt[1] += top_event[1].to_f
> 
> ```

This might be easier to understand:

#Create a hash, so that when you use a  
#key that doesn’t exist, it creates the key,  
#assigns it the array [0,0], and returns the  
#array:  
categories = Hash.new() do |hash, key|  
hash[key] = [0,0]  
end

#Loop over each line in a file:  
File.foreach(“data.txt”) do |line|  
arr = line.split(“:”)  
cat = arr[0].strip  
val = Float(arr[1]) #causes an error if can’t convert

categories[cat][0] += 1  
categories[cat][1] += val  
end

p categories  
puts categories[“Make pie”][0]  
puts categories[“Redo size”][1]

Using this data:

Redo size: 1.1  
Logical reads: 2.1  
Redo size: 1.1  
Hello world: 3.1  
Make pie: 4.1  
Hello world: 3.1  
Make pie: 4.1  
Make pie: 4.1

this is the output:

{“Make pie”=\>[3, 12.3], “Hello world”=\>[2, 6.2], “Redo size”=\>[2, 2.2],

“Logical reads”=\>[1, 2.1]}  
3  
2.2
