From 5241b97709c693f272d457abc9165e7d750330b3 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 9 Jul 2006 20:48:31 +0000 Subject: Optional identity for Enumerable#sum defaults to zero. Closes #5657. git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4599 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- activesupport/lib/active_support/core_ext/enumerable.rb | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'activesupport/lib/active_support/core_ext/enumerable.rb') diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb index 92304a23f6..59128007df 100644 --- a/activesupport/lib/active_support/core_ext/enumerable.rb +++ b/activesupport/lib/active_support/core_ext/enumerable.rb @@ -30,7 +30,14 @@ module Enumerable #:nodoc: # # Also calculates sums without the use of a block: # [5, 15, 10].sum # => 30 - def sum(&block) + # + # The default identity (sum of an empty list) is zero. + # However, you can override this default: + # + # [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0) + # + def sum(identity = 0, &block) + return identity unless size > 0 if block_given? map(&block).sum else -- cgit v1.2.3