Finding the sum of all the numbers between a and b: Ruby

Viewed 998

Been working on this Kata for quite some time now and still can't figure out what I'm missing. The question is given two integers a and b, which can be positive or negative, find the sum of all the numbers between including them too and return it. If the two numbers are equal return a or b.

So far this is what my solution looks like:

def get_sum(a,b)
  sum = [a+=b].sum      
  if sum == a or b 
    return a
  end 
end

and this is the output result:

Test Passed: Value == 1
Test Passed: Value == 3
Expected: 14, instead got: 4
Expected: 127759, instead got: 509
Expected: 44178, instead got: 444

I believe the keyword is all the numbers between but I'm not sure how to write that syntactically. I've included some examples below for further clarification.

get_sum(1, 0) == 1   # 1 + 0 = 1
get_sum(1, 2) == 3   # 1 + 2 = 3
get_sum(0, 1) == 1   # 0 + 1 = 1
get_sum(1, 1) == 1   # 1 Since both are same
get_sum(-1, 0) == -1 # -1 + 0 = -1
get_sum(-1, 2) == 2  # -1 + 0 + 1 + 2 = 2

https://www.codewars.com/kata/55f2b110f61eb01779000053/train/ruby

4 Answers

Your code does not return result except for a=b case. Also - what [a+=b] generates? Array with a single element a+b, so it's sum is just a+b

Make a range and get it's sum.

Added: parameter ordering

def get_sum(a,b)
    a, b = b, a if a > b
    return (a..b).sum      
end

print get_sum(1,3)
print get_sum(2,2)
print get_sum(-1,2)
print get_sum(3,-1)

>> 6 2 2 5

Please, try with below and ref enter link description here:

def get_sum(a,b)
  return a if a == b  
  return (a..b).sum if b > a
  return (b..a).sum if a > b
end

Test:

describe "Example Tests" do
  Test.assert_equals(get_sum(1,1),1)
  Test.assert_equals(get_sum(0,1),1)
  Test.assert_equals(get_sum(0,-1),-1)
  Test.assert_equals(get_sum(1,2),3)
  Test.assert_equals(get_sum(5,-1),14)
end

Outout:

Test Results:
 Example Tests
Test Passed: Value == 1
Test Passed: Value == -1
Test Passed: Value == 3
Test Passed: Value == 14
You have passed all of the tests! :)
def get_sum(a,b)
  sum = [a+=b].sum      
  if sum == a or b 
    return a
  end 
end

Other answers explain what you could write instead, so let's check your code:

  • a+=b is called first. It's basically a = a + b, so it calculates the sum of both inputs, saves it in a, and returns a.
  • sum = [a].sum creates an array with one element, and calculates its sum (which is just this one element). So sum = a
  • a or b is just a when a is truthy (that is, neither false nor nil).

So here's what your code actually does:

def get_sum(a,b)
  a = a + b
  sum = a
  if sum == a
    return a
  end 
end

Which is just:

def get_sum(a,b)
  a = a + b
  return a
end

Or :

def get_sum(a,b)
  a = a + b
end

or :

def get_sum(a,b)
  a + b
end
Related