[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: better way to accumulate totals

ara.t.howard

10/30/2007 9:07:00 PM


On Oct 30, 2007, at 2:41 PM, Robert Keller wrote:

>
> Below is part of a big loop that goes through each found line for
> each document, and is in its own method.
>
> 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
>

count = Hash.new{|h,k| h.update k => Hash.new{|h,k| h.update k => 0}}

case top_event[0].strip
when /redo size:/i
count[:redo][0] += 1
count[:redo][1] += Float(top_event[1])

when /logical reads:/i
count[:read][0] += 1
count[:read][1] += 1

...

require 'yaml'

y count


is one approach.

cheers.

a @ http://codeforp...
--
we can deny everything, except that we have the possibility of being
better. simply reflect on that.
h.h. the 14th dalai lama




3 Answers

Joel VanderWerf

10/30/2007 9:40:00 PM

0

ara.t.howard wrote:
> count = Hash.new{|h,k| h.update k => Hash.new{|h,k| h.update k => 0}}

This works...

count = Hash.new{|h,k| h[k] = Hash.new{|h1,k1| h1[k1] = 0}}
=> {}
count[:foo][1] += 1
=> 1
count[:foo][1] += 1
=> 2
count[:foo][1] += 1
=> 3


--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

ara.t.howard

10/30/2007 9:48:00 PM

0


On Oct 30, 2007, at 3:40 PM, Joel VanderWerf wrote:

> This works...
>
> count = Hash.new{|h,k| h[k] = Hash.new{|h1,k1| h1[k1] = 0}}
> => {}
> count[:foo][1] += 1
> => 1
> count[:foo][1] += 1
> => 2
> count[:foo][1] += 1
> => 3

oh yeah, of course ;-) i'm in the habbit of using 'update' from
'inject' where is saves you having to return the hash itself...
shorter is better always.

cheers.

a @ http://codeforp...
--
it is not enough to be compassionate. you must act.
h.h. the 14th dalai lama




Joel VanderWerf

10/30/2007 10:07:00 PM

0

ara.t.howard wrote:
>
> On Oct 30, 2007, at 3:40 PM, Joel VanderWerf wrote:
>
>> This works...
>>
>> count = Hash.new{|h,k| h[k] = Hash.new{|h1,k1| h1[k1] = 0}}
>> => {}
>> count[:foo][1] += 1
>> => 1
>> count[:foo][1] += 1
>> => 2
>> count[:foo][1] += 1
>> => 3
>
> oh yeah, of course ;-) i'm in the habbit of using 'update' from
> 'inject' where is saves you having to return the hash itself... shorter
> is better always.

...but only if returning the hash is the right thing to do. In this
case, we want the "leaf" value, not the hash:

irb(main):034:0> count = Hash.new{|h,k| h.update k => Hash.new{|hh,kk|
hh.update kk => 0}}
=> {}
irb(main):035:0> count[:foo][1] += 1
NoMethodError: undefined method `+' for {1=>{}, :foo=>{}}:Hash
from (irb):35
irb(main):036:0> count
=> {1=>{}, :foo=>{}}

--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407