2017-06-23 45 views
1

如果if語句轉到'else',可以讓重複if語句嗎?如果轉到'else',重複if語句

這是一個代碼的一部分:

puts "While you are walking you find a small jar containing honey. Do 
you take it? yes/not" 

choice = $stdin.gets.chomp 

if choice.include?("yes") 
    honey = true 
    puts " " 
    puts "You put the small honey jar in your bag and then keep walking." 

elsif choice.include?("not") 
    puts "Ok! maybe you are right. Better leave it!" 
    puts "You keep going" 
    honey = false 

else 
    " " 
    puts "Answer yes or not." 

end 

所以我想,如果用戶不是或不是那種if語句再次運行,可能再次提出的問題或只是給了「其他'的信息,並再次給出寫出答案的可能性。謝謝。

回答

0

你可以用它放在一個循環:

loop do 
    puts "While you are walking you find a small jar containing honey. Do 
    you take it? yes/not" 

    choice = $stdin.gets.chomp 

    if choice.include?("yes") 
    honey = true 
    puts " " 
    puts "You put the small honey jar in your bag and then keep walking." 
    break 
    elsif ... 
    ... 
    break 
    else 
    puts "Answer yes or not." 
    end 

end 

如果不明確地從迴路斷線(當用戶給出預期輸入你這樣做),那麼它會自動重新運行。

+0

感謝的提示。但是,在這種情況下,我決定使用'while'而不是'loop do',因爲在循環中我需要修改局部變量並在循環之後使用它。使用'while'這可能與'循環做'這不是。本地變量不會被修改。 –

+0

@MarcoVanali:它仍然是一個循環:)你也可以看看埃裏克的答案。很有用。 –

1

如果你正在編寫一個基於文本的遊戲,你可能希望定義一個方法:

def ask(question, messages, choices = %w(yes no), values = [true, false]) 
    puts question 
    puts choices.join('/') 
    choice = $stdin.gets.chomp 
    message, choice, value = messages.zip(choices, values).find do |_m, c, _v| 
    choice.include?(c) 
    end 
    if message 
    puts message 
    value 
    else 
    puts "Please answer with #{choices.join(' or ')}" 
    puts 
    end 
end 

question = 'While you are walking you find a small jar containing honey. Do you take it?' 
messages = ['You put the small honey jar in your bag and then keep walking.', 
      "Ok! maybe you are right. Better leave it!\nYou keep going"] 

honey = ask(question, messages) while honey.nil? 
puts honey 

這將循環,直到一個有效的答案提供。

舉個例子:

While you are walking you find a small jar containing honey. Do you take it? 
yes/no 
who cares? 
Please answer with yes or no 

While you are walking you find a small jar containing honey. Do you take it? 
yes/no 
okay 
Please answer with yes or no 

While you are walking you find a small jar containing honey. Do you take it? 
yes/no 
yes 
You put the small honey jar in your bag and then keep walking. 
true