Christoph R.
10/24/2003 1:26:00 PM
Gavin Sinclair wrote:
...
> When I define it like this
>
> def sum
> result = 0
> self.each { |elt| result += yield(elt) }
> result
> end
>
> {1=>2}.sum { |k,v| v } works but gives a warning.
> [[1,2]].sum { |a,b| b } is fine.
Actually it is the other way around - the second ``sum''
is issuing the warning and first runs perfectly okay!
Here is a possible solution by distinguishing between
``normal'' enumerables and enumerables yielding
possibly several values at the same time (e.g. hashes).
---
module Enumerable
def sum
result = 0
each { |elt| result += yield(elt) }
result
end
module Many
def sum
result = 0
each { |*elt| result += yield(*elt) }
result
end
end
end
class Hash
include Enumerable::Many
end
# sum of second elements
h = Hash[1,2,3,4]
p h.sum { |a,b| b } # 6
p h.to_a.sum {|a,b| b } # 6
---
This script should run danty without warnings.
/Christoph