简体   繁体   中英

Begin rescue retry error

If this code executes the else statement, I want it to retry either from rescue or from begin . Running the code asks me for an input and, when I input it, the code doesn't work.

1- What can I do to make this code work with the else statement running the retry ?

2- Why does removing rescue create a retry Syntax Error ?

# Creates input method
def input
  x = gets.to_i
end

#Begins the first choice
begin

  puts "What will you do?
  1- Get a closer look
  2- Go in the opposite direction
  Write your input an press enter:"
rescue
  #Calls input method
  choice = input
  if choice == 1
    puts "You get a closer look and..."
  elsif choice == 2
    puts "You go in the opposite direction, out of trouble"
  else 
    puts "Incorrect input, enter a number between the one's avaliables:"
  end

  #Retries if the choice is error
retry if choice != 1||2
end

Using a rescue block is for handling exceptions, I really don't think it's needed here. A loop will do the job.

puts "What will you do?",
     "1- Get a closer look",
     "2- Go in the opposite direction",
     "Write your input and press enter:"

loop do
  choice = gets.to_i
  if choice == 1
    puts "You get a closer look and..."
    break
  elsif choice == 2
    puts "You go in the opposite direction, out of trouble"
    break
  else
    puts "Incorrect input, enter a number between the ones available:"
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM