2017-06-23 5 views
1

'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 

だから私は文が再び実行する場合であれば、ユーザは多分、再び質問をするか、単に「他を与え、yesと入力かしていないことを希望返答を書く可能性を再び与えている。ありがとう。

答えて

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'を使うと 'loop do'でこれが可能ですが、これはできません。ローカル変数は変更されません。 –

+0

@MarcoVanali:これはまだループです:) Ericの答えを見ることもできます。非常に便利。 –

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