我正在用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
答案 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”会发生这种情况)。