Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added Enumerable#sum for calculating a sum from the elements [DHH]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4489 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
commit fd0eaaa407fb8fd704967be2734c1b094ac630d9 1 parent 8b89bd7
@dhh dhh authored
View
7 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]
View
14 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 @@ def group_by
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
View
9 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 @@ def test_group_by
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
Please sign in to comment.
Something went wrong with that request. Please try again.