From 236c7325df4ca2783c92dffc0f0b9592f822d95a Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 25 Jun 2006 19:11:09 +0000 Subject: Enumerable#sum without blocks. Closes #5505. Don't assume 0 identity for sum. git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4495 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- activesupport/lib/active_support/core_ext/enumerable.rb | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) (limited to 'activesupport/lib/active_support') diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb index 0d7d0159f9..92304a23f6 100644 --- a/activesupport/lib/active_support/core_ext/enumerable.rb +++ b/activesupport/lib/active_support/core_ext/enumerable.rb @@ -26,11 +26,18 @@ module Enumerable #:nodoc: # payments.sum { |p| p.price * p.tax_rate } # payments.sum(&:price) # - # This is instead of payments.inject(0) { |sum, p| sum + p.price } - def sum - inject(0) { |sum, element| sum + yield(element) } + # This is instead of payments.inject { |sum, p| sum + p.price } + # + # Also calculates sums without the use of a block: + # [5, 15, 10].sum # => 30 + def sum(&block) + if block_given? + map(&block).sum + else + inject { |sum, element| sum + element } + end end - + # Convert an enumerable to a hash. Examples: # # people.index_by(&:login) @@ -45,4 +52,4 @@ module Enumerable #:nodoc: end end -end \ No newline at end of file +end -- cgit v1.2.3