Jack Kelly Jack Kelly - 1 month ago 9
Ruby Question

I am unable to break a loop that repeatedly asks for user input. Anyone know how to solve this?

I am trying to create a loop that will ask the user for an integer and will then print "hi" an integer number of times and then ask for input again. I then want the loop to break if the user inputs "bye".

my code so far:

def hi_hi_goodbye
loop do
number = gets

(number.to_i).times do
print "hi"
end

break if
gets == "bye"
end

end


My code so far will not loop. It receives the integer and prints "hi" a given amount of times. However, I am unable to break the loop.

Answer

Try

 break if gets.chomp == "bye"

This is so because your input would be something like bye\n, so your condition always false, because gets takes even the enter.

Comments