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?
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]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.