in reply to Re: List::Util::sum() and empty lists...
in thread List::Util::sum() and empty lists...

Yeah, the Ruby way to do this is to use inject and pass the appropriate seed value for the operation. If you don't like the explicitness there you can always hide it by extending Enumerable yourself.

module Enumerable def sum( ) inject( 0 ) { |m,x| m += x } ; end def prod( ) inject( 1 ) { |m,x| m *= x } ; end end

Additionally: As to the original question (changing to return 0 by default), you kind of loose information that way in that you don't know if you had an empty list versus having a list which just happened to sum to zero. Of course you could always explicitly check for that (presuming you have the original list around) if you needed to know. (So chalk this up as a wishy washy non-comittal neither condemnation nor approval of the proposal. :)