Reputation: 107
I want to input 2 numbers and calculate the total of the numbers in between the 2 numbers and it self. eg (1,3) 1+2+3 = 6
I have tried the code below, this works with 2 positives however this does not add up positive + negative and returns 0 everytime
def get_sum(a,b)
if a > b || a < b
num_array = (a..b).to_a.sum
puts num_array
else
puts a
end
end
get_sum(2,-3)
expected -3 instead returns 0
Upvotes: 3
Views: 1541
Reputation: 11
(x..y).to_a.sum
where x is the range starting number and y is the last element.
Refer to:
https://ruby-doc.org/core-2.2.0/Range.html
Upvotes: 1
Reputation: 11193
Just for fun, mixing up for Ruby 2.6:
x, y = 2, -3
[x,y].tap{ |a| a.reverse! if a[0] > a[1] }.then{ |x,y| (x..y).sum }
#=> -3
Upvotes: 0
Reputation: 110685
You want the sum of an algebraic series.
def get_sum(a,b)
((a-b).abs+1)*(a+b)/2
end
get_sum( 1, 4) #=> 10
get_sum( 4, 1) #=> 10
get_sum(-4, -1) #=> -10
get_sum(-1, -4) #=> -10
get_sum(-3, 4) #=> 4
get_sum( 4, -3) #=> 4
get_sum(-4, 3) #=> -4
get_sum( 3, -4) #=> -4
(a-b).abs+1
is the number of elements in the series.
Upvotes: 6
Reputation: 2222
What you can do is reverse the order of the numbers if the end value is greater than the beginning value:
a, b = b, a if a > b
According to the book "Programming Ruby", the Range object stores the two endpoints of the range and uses the .succ member to generate the intermediate values.
Upvotes: 4