Thank you for the very clear and helpful explanation!
Robert K.
[email protected]
----- Original Message ----
From: 7stud – [email protected]
To: ruby-talk ML [email protected]
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