Skip to content

Commit

Permalink
Enumerable#sum now works will all enumerables, even if they don't res…
Browse files Browse the repository at this point in the history
…pond to :size

[#2489 state:committed]

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
  • Loading branch information
marcandre authored and jeremy committed Aug 9, 2009
1 parent 3b37985 commit 2909626
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
6 changes: 2 additions & 4 deletions activesupport/lib/active_support/core_ext/enumerable.rb
Expand Up @@ -55,12 +55,10 @@ def group_by
# [].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

Expand Down
4 changes: 4 additions & 0 deletions activesupport/test/core_ext/enumerable_test.rb
Expand Up @@ -60,6 +60,10 @@ def test_empty_sums
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)
Expand Down

0 comments on commit 2909626

Please sign in to comment.