如何跳到红宝石线

时间:2018-09-15 17:39:46

标签: ruby

我正在用ruby开发一个pwd生成器,当到达代码的某个点时,如果用户说他想重试生成pwd,则需要返回。

print "do you want to retry to generate the password? [y/n]"
    retrypwd = gets.chomp
    if retrypwd == y
    (code to jump to some lines ago)
    elsif retrypwd == n
    print "Ok, It'll be for the next time"
end

1 个答案:

答案 0 :(得分:4)

诀窍是使用loop并根据您的期望将其破坏或重复:

def try_again?
  loop do
    print "Would you like to try again? Y/N"
    again = gets.chomp.capitalize

    case (again)
    when 'N'
      return false
    when 'Y'
      return true
    else
      puts "Huh? I don't know what that means."
    end
  end
end

然后您可以将其合并到主程序中:

begin
  try_password
end while try_again?

您将继续尝试输入密码,直到try_again?返回false(如果您键入“ N”会发生这种情况)。