Permalink
Browse files

Enumerable#sum now works will all enumerables, even if they don't res…

…pond to :size

[#2489 state:committed]

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
  • Loading branch information...
1 parent 3b37985 commit 29096268ccce2b13e1490c8b673ffe0b498555fc @marcandre marcandre committed with jeremy Apr 14, 2009
@@ -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
@@ -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)

0 comments on commit 2909626

Please sign in to comment.