1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

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
This commit is contained in:
David Heinemeier Hansson 2006-06-24 16:14:59 +00:00
parent 8b89bd779a
commit fd0eaaa407
3 changed files with 28 additions and 2 deletions

View file

@ -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 file

@ -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

View file

@ -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