Browse files

Optimize Range#sum only for integers [#2489]

  • Loading branch information...
1 parent 1185500 commit e0adfa82c05f9c975005f102b4bcaebfcd17d241 @josevalim josevalim committed with lifo Aug 9, 2009
View
5 activesupport/lib/active_support/core_ext/enumerable.rb
@@ -113,9 +113,10 @@ def none?(&block)
end
class Range #:nodoc:
- # Optimize range sum to use arithmetic progression if a block is not given.
+ # Optimize range sum to use arithmetic progression if a block is not given and
+ # we have a range of numeric values.
def sum(identity=0, &block)
- return super if block_given?
+ return super if block_given? || !(first.instance_of?(Integer) && last.instance_of?(Integer))
actual_last = exclude_end? ? (last - 1) : last
(actual_last - first + 1) * (actual_last + first) / 2
end
View
1 activesupport/test/core_ext/enumerable_test.rb
@@ -64,6 +64,7 @@ def test_enumerable_sums
assert_equal 20, (1..4).sum { |i| i * 2 }
assert_equal 10, (1..4).sum
assert_equal 6, (1...4).sum
+ assert_equal 'abc', ('a'..'c').sum
end
def test_each_with_object

0 comments on commit e0adfa8

Please sign in to comment.