Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #6487 from avakhov/range-sum-optimization

Fix Range#sum optimized version
  • Loading branch information...
commit 8e1d46c7e197bb904b07b7f677ab4593030d57d2 2 parents 56417b4 + b4167d3
@rafaelfranca rafaelfranca authored
View
8 activesupport/lib/active_support/core_ext/enumerable.rb
@@ -65,11 +65,15 @@ class Range #:nodoc:
# 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)
- if block_given? || !(first.instance_of?(Integer) && last.instance_of?(Integer))
+ if block_given? || !(first.is_a?(Integer) && last.is_a?(Integer))
super
else
actual_last = exclude_end? ? (last - 1) : last
- (actual_last - first + 1) * (actual_last + first) / 2
+ if actual_last >= first
+ (actual_last - first + 1) * (actual_last + first) / 2
+ else
+ identity
+ end
end
end
end
View
5 activesupport/test/core_ext/enumerable_test.rb
@@ -84,6 +84,11 @@ def test_range_sums
assert_equal 10, (1..4.5).sum
assert_equal 6, (1...4).sum
assert_equal 'abc', ('a'..'c').sum
+ assert_equal 50_000_005_000_000, (0..10_000_000).sum
+ assert_equal 0, (10..0).sum
+ assert_equal 5, (10..0).sum(5)
+ assert_equal 10, (10..10).sum
+ assert_equal 42, (10...10).sum(42)
end
def test_index_by
Please sign in to comment.
Something went wrong with that request. Please try again.