From 0830b6a650431e9405801afa5d1b45532885707d Mon Sep 17 00:00:00 2001 From: Marc-Andre Lafortune Date: Tue, 14 Apr 2009 01:12:55 -0400 Subject: [PATCH] Enumerable#sum now works will all enumerables, even if they don't respond to :size --- .../lib/active_support/core_ext/enumerable.rb | 6 ++---- activesupport/test/core_ext/enumerable_test.rb | 4 ++++ 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb index a7eaccf..2c5f59b 100644 --- a/activesupport/lib/active_support/core_ext/enumerable.rb +++ b/activesupport/lib/active_support/core_ext/enumerable.rb @@ -55,12 +55,10 @@ module Enumerable # [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0) # def sum(identity = 0, &block) - return identity unless size > 0 - if block_given? - map(&block).sum + map(&block).sum(identity) else - inject { |sum, element| sum + element } + inject { |sum, element| sum + element } || identity end end diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb index 92db977..026c8c8 100644 --- a/activesupport/test/core_ext/enumerable_test.rb +++ b/activesupport/test/core_ext/enumerable_test.rb @@ -58,6 +58,10 @@ class EnumerableTests < Test::Unit::TestCase assert_equal Payment.new(0), [].sum(Payment.new(0)) end + def test_enumerable_sums + assert_equal 10, (1..4).sum + end + def test_each_with_object result = %w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase } assert_equal({'foo' => 'FOO', 'bar' => 'BAR'}, result) -- 1.5.6.4