Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop a request for user input until the user enters the correct info?

I am a beginner who is trying to learn Ruby. I have learned some of the easier stuff so far, but I seem to be stuck in trying to combine a couple of things I've learned.

What I am trying to do is to ask the user a question and tell them to enter either 1 or 2. A simple if statement would let me respond with one option if they enter 1, and another option if they enter 2. However, if they enter something entirely different like a different number, a string, etc., how can I prompt them to try again and have it loop back to the original question?

What I have so far looks something like this.

prompt = "> " 
puts "Question asking for 1 or 2." 
print prompt
user_input = gets.chomp.to_i

if user_input == 1    
   puts "One response." 
elsif user_input == 2   
   puts "Second response." 
else    
   puts "Please enter a 1 or a 2." 
end

This is where I'm stuck. How do I make it go back to the "Question asking for 1 or 2." until the user enters a 1 or 2? I know it's probably a loop of some kind, but I can't seem to figure out which kind to use and how to incorporate asking for user input repeatedly (if necessary) until getting the desired input. Any help would be greatly appreciated. Thanks.

like image 750
Bushido Code Avatar asked Dec 04 '13 22:12

Bushido Code


2 Answers

You're right that you need to run your code in a loop. Using a while loop with gets.chomp as a condition, you can carry on asking for user input until you decide you've got what you want.

In this case, you want to validate the answer to the question and ask again if it's invalid. You don't need to change a great deal, except making sure you break out of the loop when the answer is correct. If the answer is wrong, print the prompt again.

This is a slightly refactored version that uses case instead, but it shows what you need to do. There is no doubt a cleaner way to do this...

prompt = "> "
puts "Question asking for 1 or 2."
print prompt

while user_input = gets.chomp # loop while getting user input
  case user_input
  when "1"
    puts "First response"
    break # make sure to break so you don't ask again
  when "2"
    puts "Second response"
    break # and again
  else
    puts "Please select either 1 or 2"
    print prompt # print the prompt, so the user knows to re-enter input
  end
end
like image 188
mrlee Avatar answered Sep 24 '22 21:09

mrlee


Try using the until method like this:

prompt = "> " 
print prompt

user_input = nil
until (user_input == 1 or user_input == 2)
    puts "Please enter a 1 or 2." 
    user_input = gets.chomp.to_i
end



if user_input == 1    
   puts "One response." 
elsif user_input == 2   
   puts "Second response." 
else    
   puts "Please enter a 1 or a 2." 
end
like image 39
Josh Avatar answered Sep 25 '22 21:09

Josh