How do I program a request for user input until the user enters the correct information?

I am a newbie who is trying to recognize Ruby. So far, I have learned some of the simplest things, but it seems like I'm stuck in trying to combine a couple of things that I have learned.

What I'm trying to do is ask the user a question and tell them to enter either 1 or 2. The simple if statement allowed me to answer with one option if they enter 1, and another option if they enter 2. However, if they enter something completely different, for example, a different number, line, etc., How can I ask them to try again and return to the original question?

What I still look 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

. " 1 2." 1 2? , , , - , , ( ) . . .

+4
4

, . while gets.chomp , , , , .

, . , , , . , .

, case, , . , ...

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
+6
    user_input = 0
    until [1,2].include? user_input do
        puts "Please enter a 1 or a 2.>" 
        user_input = gets.chomp.to_i
    end
    if user_input == 1    
        puts "One response." 
    else   
        puts "Second response." 
    end

, .

+1

until :

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
0

, . , : Ruby Retry ,

Using error detection and the unique keyword retryavailable in Ruby allows you to easily execute a retry loop, compressed along with nice error handling.

However, remember that the example I pointed out is actually not the best. There are some minor issues. For example, you should not catch Exception, simple enough rescue => e. But the general idea should be pretty clear.

0
source

All Articles