Using sum on negative integers in array

Hi ruby-foum!

I’m trying to find the sum of all of the integers within a given range, up to and including the base and highest integer:

def get_sum(a,b)
@a = a
@b = b

if @a == @b
return @a

return (@a@b).to_a.sum


this works fine on positive integers. however,


returns 0. I would expect -1?

The key part is the expression @[email protected], where @a should be the start and @b the end of your range.

Try this in irb:

> (0...10).to_a
 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
> (0...-1).to_a
=> []
> (-1...0).to_a
=> [-1]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs