Alvaro R Alvaro R - 16 days ago 6
Ruby Question

Begin rescue retry error

If this code runs the "else" statement, I want it to retry from "rescue" or from "begin", i don't mind.
Runnig the code ask me for an input and, when I put it, it doesn't work.

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

2- Eliminating "rescue" creates a "retry Syntax Error" Why?

# 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


THANKS!

Answer

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