mirror of
https://github.com/github/rails.git
synced 2026-04-26 03:00:59 -04:00
Optimize Range#sum only for integers [#2489]
This commit is contained in:
@@ -113,9 +113,10 @@ module Enumerable
|
||||
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
|
||||
|
||||
@@ -64,6 +64,7 @@ class EnumerableTests < Test::Unit::TestCase
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user