My code should prompt the user to input numbers until they type 'stop', when it returns the total of the numbers entered. I've written this program two ways, both of which fail to break the loop when 'stop' is entered.
My first attempt was with an until loop, although I feel the control flow doesn't work as well. My second uses 'until true' and 'break'. I'm storing the result of gets in a variable so that I can convert it to an integer, and I've tested removing the variable in case 'stop' was being converted.
# 2nd attempt
total = 0
while true
puts "Give me a number"
gets_var = gets
if gets_var == "stop"
break
else
total += gets_var.to_i
end
end
puts total
# 1st attempt
total = 0
gets_var = 0
until gets_var == "stop"
puts "Give me a number"
gets_var = gets
total += gets_var.to_i
end
puts total
I expect inputting 'stop' when prompted to end the loop and return the total. In no case does 'stop' break the loop.
Why is my loop failing to break?
gets_var
contains a newline at the end. And so it can't be equal to"stop"