I assume that the ranges whose sums are to be calculated are integer ranges.
def range_sum(rng)
rng.size * (2 * rng.first + rng.size - 1) / 2
end
range_sum(4..10)
range_sum(4...10)
range_sum(-10..10)
Defining
last = rng.first + rng.size - 1
expression
rng.size * (2 * rng.first + rng.size - 1) / 2
comes down to
rng.size * (rng.first + last) / 2
which is just a formula for the sum of the values of an arithmetic progression. Note (4..10).size #=> 7and (4...10).size #=> 6.
source
share