1
votes

I have written a program for codewars that finds the lowest two integers and returns the sum of them:

def sum_two_smallest_numbers(numbers)
  array_lowest = [0, 0]
  main_iterate = 2
  array_lowest[0] = sum_two_smallest_numbers[0]
  array_lowest[1] = sum_two_smallest_numbers[1]
  until main_iterate == sum_two_smallest_numbers.length - 1 #maybe -2, or 0
    if sum_two_smallest_numbers[main_iterate] < array_lowest[0]
      array_lowest[0] = sum_two_smallest_numbers[main_iterate]
      main_iterate += 1
    elsif sum_two_smallest_numbers[main_iterate] < array_lowest[1]
      array_lowest[1] = sum_two_smallest_numbers[main_iterate]
      main_iterate += 1
    else
      main_iterate += 1
    end
  end
  return array_lowest[0] + array_lowest[1]
end

to fulfill tests as follows:

Test.assert_equals(sum_two_smallest_numbers([5, 8, 12, 18, 22]), 13) 
Test.assert_equals(sum_two_smallest_numbers([7, 15, 12, 18, 22]), 19) 
Test.assert_equals(sum_two_smallest_numbers([25, 42, 12, 18, 22]), 30) 

It complains about my first line (this was provided along with an end), and if I replace numbers with any actual numbers, as in the test cases, it throws this:

syntax error, unexpected tINTEGER, expecting ')'

How can I solve this?

1
you can't replace (numbers) with actual numbers becausse that's the list of arguments. The only place you can supply actual numbers is when you call the function (not when you define it) - max pleaner
Thanks, I've just tried calling the function. Now it sees a single number or array as 0 arguments, but more than 1 as too many. I can only get 0 or 2+. - Jules
You're going to like Ruby. Here you can write [5, 8, 12, 18, 22].min(2).sum #=> 13. See Array#min and Array#sum. - Cary Swoveland
That's such an elegant solution, and here's me reprogramming the wheel! I'm liking it already. - Jules

1 Answers

1
votes

You're recursively calling sum_two_smallest_numbers with no arguments., and it requires an argument. Each time you write sum_two_smallest_numbers, that's a method invocation. When you write sum_two_smallest_numbers[0], that's a method invocation with no arguments, the [0] would access the 0'th element of the returned value, if the invocation succeeded.

It seems like you might have wanted numbers[0], sum_two_smallest_numbers[0].