Jack Kelly Jack Kelly - 1 year ago 55
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"

break if
gets == "bye"


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 Source


 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download