将用户带回代码的开头

时间:2013-12-03 18:36:37

标签: ruby-on-rails ruby

我正在尝试通过Ruby创建一个二十一点游戏。我正在编写介绍部分,Ruby将询问用户是否打算使用“是或否”选项来玩游戏。

如果用户输入“No”,Ruby会询问“你确定吗?” 从这里开始,如果用户再次输入“No”,我希望Ruby再次将用户带回到程序的开头。

# Blackjack Game introduction

puts "Welcome! Are we ready to play? Yes or No"
answer = gets.chomp

if answer == "Yes"
    puts "Great! What is your name?"
    user_name = gets.chomp
    name = [] << user_name
    puts "Alright #{user_name}! Let's play!"
elsif
    puts "Are you sure you want to exit? Yes or No"
    user_answer = gets.chomp
  if user_answer == "No"
    retry
  end
end

“重试”方法会给我一个错误... 非常感谢你!

3 个答案:

答案 0 :(得分:2)

您希望代码位于beginend语句中:

begin
  puts "Welcome! Are we ready to play? Yes or No"
  answer = gets.chomp

  if answer == "Yes"
    puts "Great! What is your name?"
    user_name = gets.chomp
    name = [] << user_name
    puts "Alright #{user_name}! Let's play!"
  elsif
    puts "Are you sure you want to exit? Yes or No"
    user_answer = gets.chomp
    if user_answer == "No"
      retry
    end
  end
end

great tutorial讨论retry并提供示例。

答案 1 :(得分:1)

你的游戏是一个无限循环,用户将会突破。所以放在一切:

while true

end

然后将retry替换为break。 (而且,在这个阶段,阅读教程的质量时间不会让你失望。)

答案 2 :(得分:0)

puts "Welcome! Are we ready to play? Yes or No"
while play_answer = gets.chomp
  if play_answer == "Yes"
    puts "Great! What is your name?"
    user_name = gets.chomp
    puts "Alright #{user_name}! Let's play!"
  else
    puts "Are you sure you want to exit? Yes or No"
    exit_answer = gets.chomp
    if exit_answer == "Yes"
      puts "Goodbye"
      break
    end
  end
end