2017-06-23 81 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