diff options
-rw-r--r-- | activesupport/CHANGELOG | 7 | ||||
-rw-r--r-- | activesupport/lib/active_support/core_ext/enumerable.rb | 14 | ||||
-rw-r--r-- | activesupport/test/core_ext/enumerable_test.rb | 9 |
3 files changed, 28 insertions, 2 deletions
diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index 092c42ed3f..ed820edd73 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,5 +1,12 @@ *SVN* +* Added Enumerable#sum for calculating a sum from the elements [DHH]. Examples: + + payments.sum { |p| p.price * p.tax_rate } + payments.sum(&:price) + + This is instead of payments.inject(0) { |sum, p| sum + p.price } + * Correct and clarify Array#to_sentence docs. #5458 [brad@madriska.com] * alias_method_chain preserves method punctuation so foo, foo?, and foo! may be chained with the same feature. [Jeremy Kemper] diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb index 5c556ff98d..4de520f4ed 100644 --- a/activesupport/lib/active_support/core_ext/enumerable.rb +++ b/activesupport/lib/active_support/core_ext/enumerable.rb @@ -1,3 +1,5 @@ +require File.dirname(__FILE__) + '/enumerable/injections' + module Enumerable #:nodoc: # Collect an enumerable into sets, grouped by the result of a block. Useful, # for example, for grouping records by date. @@ -20,4 +22,14 @@ module Enumerable #:nodoc: groups end end -end + + # Calculates a sum from the elements. Examples: + # + # 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) } + end +end
\ No newline at end of file diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb index df14200e42..882111cd79 100644 --- a/activesupport/test/core_ext/enumerable_test.rb +++ b/activesupport/test/core_ext/enumerable_test.rb @@ -1,8 +1,9 @@ require 'test/unit' require File.dirname(__FILE__) + '/../../lib/active_support/core_ext/enumerable' +Payment = Struct.new(:price) + class EnumerableTests < Test::Unit::TestCase - def test_group_by names = %w(marcel sam david jeremy) klass = Class.new @@ -17,4 +18,10 @@ class EnumerableTests < Test::Unit::TestCase assert group.all? {|person| person.name == name} end end + + def test_sums + payments = [ Payment.new(5), Payment.new(15), Payment.new(10) ] + assert_equal 30, payments.sum(&:price) + assert_equal 60, payments.sum { |p| p.price * 2 } + end end |