S
SpringFlowers AutumnMoon
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
@total += new_value # new value in
super
end
def inspect
super + " total = #{@total}"
end
end
t = Tally.new
t["apple"] += 1
puts; p t
t["banana"] += 1
puts; p t
t["banana"] = 1000
puts; p t
t["apple"] += 10
puts; p t
t["apple"] -= 5
puts; p t
t["apple"] = 10000
puts; p t
t[123] = 10
puts; p t
[~/depot] 360 $ ruby test_tally.rb
{"apple"=>1} total = 1
{"apple"=>1, "banana"=>1} total = 2
{"apple"=>1, "banana"=>1000} total = 1001
{"apple"=>11, "banana"=>1000} total = 1011
{"apple"=>6, "banana"=>1000} total = 1006
{"apple"=>10000, "banana"=>1000} total = 11000
{"apple"=>10000, 123=>10, "banana"=>1000} total = 11010
["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
@total += new_value # new value in
super
end
def inspect
super + " total = #{@total}"
end
end
t = Tally.new
t["apple"] += 1
puts; p t
t["banana"] += 1
puts; p t
t["banana"] = 1000
puts; p t
t["apple"] += 10
puts; p t
t["apple"] -= 5
puts; p t
t["apple"] = 10000
puts; p t
t[123] = 10
puts; p t
[~/depot] 360 $ ruby test_tally.rb
{"apple"=>1} total = 1
{"apple"=>1, "banana"=>1} total = 2
{"apple"=>1, "banana"=>1000} total = 1001
{"apple"=>11, "banana"=>1000} total = 1011
{"apple"=>6, "banana"=>1000} total = 1006
{"apple"=>10000, "banana"=>1000} total = 11000
{"apple"=>10000, 123=>10, "banana"=>1000} total = 11010