如何围绕if语句包装循环

时间:2015-01-12 23:18:44

标签: ruby

我正在编写一个程序,询问用户是否想要提供他的名字。如果用户回答“是”,则询问问题; '不',程序退出。如果用户输入任何其他内容,则会提醒他们说“是”或“否”。

到目前为止我的代码:

puts "Would you like to give us your name? (type yes or no)"
answer = gets.chomp

if answer == "yes"
  print "What's your name?"
  name = gets.chomp
  puts "Nice to meet you, #{name}"
elsif answer == "no"
  puts "Oh, ok. Good bye"
else
  puts "You need to answer yes or no"
end

如果用户没有为初始问题输入“是”或“否”,我需要重新开始。

3 个答案:

答案 0 :(得分:2)

您可以使用while循环解决该问题,只有在输入正确时才会中断。

puts "Would you like to give us your name? (type yes or no)"
while answer = gets.chomp
  case answer
  when "yes"
    print "What's your name?"
    name = gets.chomp
    puts "Nice to meet you, #{name}"
    break
  when "no"
    puts "Oh, ok. Good bye"
    break
  else
    puts "You need to answer yes or no"
  end
end

答案 1 :(得分:0)

answer = ""
while (answer != "yes" && answer != "no") do
  puts "Would you like to give us your name? (type yes or no)"
  answer = gets.chomp
end

if answer == "yes"
  print "What's your name?"
  name = gets.chomp
  puts "Nice to meet you, #{name}"
elsif answer == "no"
  puts "Oh, ok. Good bye"
else
  puts "You need to answer yes or no"
end

答案 2 :(得分:0)

创建Method

会更好

这样的事情对你有用:

def getname
  # ask the user if we should continue
  puts "Would you like to give us your name? (type yes or no)"
  answer = gets.chomp

  if answer == "yes"
    # the user said yes. get the name
    print "What's your name?"
    name = gets.chomp
  elsif answer == "no"
    # the user said no. get out of here
    puts "Oh, ok. Good bye"
  else
    # the user didnt answer correctly
    puts "You need to answer yest or no"
    # so we call this very function again
    getname
  end
end

# call the above method that we created
getname

我们在这里做的是将您的代码包装在方法声明中。在那个方法声明中,如果用户没有提供预期的输入,我们称之为非常方法。

希望这有帮助。