diff options
author | Jeremy Kemper <jeremy@bitsweat.net> | 2006-06-25 19:11:09 +0000 |
---|---|---|
committer | Jeremy Kemper <jeremy@bitsweat.net> | 2006-06-25 19:11:09 +0000 |
commit | 236c7325df4ca2783c92dffc0f0b9592f822d95a (patch) | |
tree | 09c0e8e9e49cfd3b9a0cb3bc4bd68bbbea90214e /activesupport/lib | |
parent | 42775686d2b32b66c971c0560ba2497c7f8703b2 (diff) | |
download | rails-236c7325df4ca2783c92dffc0f0b9592f822d95a.tar.gz rails-236c7325df4ca2783c92dffc0f0b9592f822d95a.tar.bz2 rails-236c7325df4ca2783c92dffc0f0b9592f822d95a.zip |
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
Diffstat (limited to 'activesupport/lib')
-rw-r--r-- | activesupport/lib/active_support/core_ext/enumerable.rb | 17 |
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 |