On 9/23/07, SpringFlowers AutumnMoon <summercoolness / gmail.com> wrote:
> for the hash
>
> ["apple" => 3, "banana" => 2]
>
> is there an instant way to tally up all the counts? (instead of looping
> through all keys and add up all counts, because the hash can be very
> big, like thousands of items, and looping can be quite expensive for CPU
> time)
>
> does the following look right?
>
> class Tally < Hash
>
> attr_reader :total
>
> def initialize
> @total = 0
> super(0)
> end
>
> def []=(key, new_value)
> @total -= self[key] # previous value goes
Nope RHS can be nil
> @total += new_value # new value in
>
> super
I would put super first just in case it crashes anyway
old_value = fetch(key,0)
begin
super
@total += new_value - old_value
rescue
HTH
Robert
--
I'm an atheist and that's it. I believe there's nothing we can know
except that we should be kind to each other and do what we can for
other people.
-- Katharine Hepburn