简体   繁体   English

开始抢救重试错误

[英]Begin rescue retry error

If this code executes the else statement, I want it to retry either from rescue or from begin . 如果此代码执行else语句,我希望它从rescuebegin重试。 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 ? 1-如何使此代码与运行retry的else语句一起工作?

2- Why does removing rescue create a retry Syntax Error ? 2-为什么取消rescue 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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