Homer
Homer

Reputation: 35

Ruby Endless Loop

I am new to Ruby. I have written the code below, its working about 90% except the else statement. The else statement triggers endless loop. I just want it to ask user to try again. Here is my code

 puts "Do you want to print something? (Y / N)"
 user = gets.chomp.downcase

 answer = true

 while answer

   if user == "y"
     puts "Something"
     answer = false
   elsif user == "n"
     puts " "
     answer = false
   else
     puts "Invalid input! Please enter Y or N"
   end

end 

Upvotes: 0

Views: 410

Answers (2)

steenslag
steenslag

Reputation: 80065

Somewhat shorter (note user has gone, the answer is now referred to as answer).

answer = ""
until (answer  == "y") or (answer == "n")
  puts 'Do you want to print something? (Y/N)'
  answer = gets.chomp.downcase 
end 

Upvotes: 4

Colto
Colto

Reputation: 622

Once you exit the else, answer is still true. If you want to re-prompt, you can move your puts and user statement into the loop.

Something like this should work.

while true # (alternately) loop do
  puts 'Do you want to print something? (Y/N)'

  case gets.chomp.downcase
  when 'y'
    puts 'foo'
    break
  when 'n'
    puts 'bar'
    break
  else
    puts 'Invalid input! Please enter Y or N'
  end
end

You can use break to exit out of your loop instead of setting up another variable. Also, this looks like a good use-case for a case statement to have some explicit cases listed.

Upvotes: 1

Related Questions