Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
Re: better way to accumulate totals
7stud --
10/30/2007 10:20:00 PM
Robert Keller wrote:
> The data lines look like this:
>
> " category value"
>
> case top_event[0].lstrip.rstrip
> when "Redo size:"
>
> $redo_cnt[0] += 1
> $redo_cnt[1] += top_event[1].to_f
>
>
>
> 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
--
Posted via
http://www.ruby-...
.
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
Re: better way to accumulate totals
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password