2016-11-22 54 views
0

如果此代碼執行else語句,我希望它可以從rescuebegin重試。 運行代碼向我詢問輸入信息,當我輸入代碼時,代碼不起作用。開始救援重試錯誤

1-我能做些什麼來使這個代碼與運行retry的else語句一起工作?

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 

回答

1

使用救援塊是處理異常,我真的不認爲這是需要在這裏。循環將完成這項工作。

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 
+0

謝謝,那正是我一直在尋找的。 :) –