如果转到'否则重复if语句。

时间:2017-06-23 09:46:30

标签: ruby

如果转到'否则可以重复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或者if语句再次运行,可能会再次询问问题或者仅仅给出' else'消息并再次给出了写答案的可能性。感谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

如果你没有明确地从循环中断开(当用户给出预期输入时你会这样做),那么它将自动重新运行。