aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/enumerable.rb
diff options
context:
space:
mode:
Diffstat (limited to 'activesupport/lib/active_support/core_ext/enumerable.rb')
-rw-r--r--activesupport/lib/active_support/core_ext/enumerable.rb17
1 files changed, 12 insertions, 5 deletions
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