diff options
author | Jeremy Kemper <jeremy@bitsweat.net> | 2006-07-09 20:48:31 +0000 |
---|---|---|
committer | Jeremy Kemper <jeremy@bitsweat.net> | 2006-07-09 20:48:31 +0000 |
commit | 5241b97709c693f272d457abc9165e7d750330b3 (patch) | |
tree | aceed61edcbc803208046a74ccd5a5d19683ae5f /activesupport/lib | |
parent | 1dc4cc030ffecb57ceffecac81215ed1d7924f3f (diff) | |
download | rails-5241b97709c693f272d457abc9165e7d750330b3.tar.gz rails-5241b97709c693f272d457abc9165e7d750330b3.tar.bz2 rails-5241b97709c693f272d457abc9165e7d750330b3.zip |
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
Diffstat (limited to 'activesupport/lib')
-rw-r--r-- | activesupport/lib/active_support/core_ext/enumerable.rb | 9 |
1 files changed, 8 insertions, 1 deletions
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 |