当用户尝试登录并输入一个不存在的用户名以及密码时,我希望名为exist_user的方法继续显示登录菜单(login_screen_selection)。问题是一旦菜单再次出现并且用户输入“ 1”(提示他们再次输入用户名),程序就会终止。我希望该方法的行为像一个无限循环,只有在您输入已经存在的用户名时才会中断
def process_login
case login_screen_selection
when '1'
existing_user
when '2'
create_account
when '3'
exit_application
else
process_login
end
end
def login_screen_selection
puts "1. Login"
puts "2. Create account"
puts "3. Exit"
gets.chomp
end
def existing_user
puts "Please Enter Username"
get_username = gets.chomp
puts "Please Enter Password"
get_password = gets.chomp
customer = Customer.find_by(
username: get_username,
password: get_password
)
if customer.nil? do
puts 'Sorry, username and/or password combination not valid. Please try again'
login_screen_selection
break if !customer.nil?
end
end
答案 0 :(得分:1)
看起来有些不错的答案。我只补充说,如果您执行以下操作,则无需检查if customer.nil?
或if customer
或其变体:
def existing_user
puts "Please Enter Username"
username = gets.chomp
puts "Please Enter Password"
password = gets.chomp
unless customer = Customer.find_by(
username: username,
password: password
)
puts 'Sorry, username and/or password combination not valid. Please try again'
process_login
end
end
答案 1 :(得分:0)
您想要一个循环,所以写一个循环:
def existing_user
while customer.nil? do
puts "Please Enter Username"
get_username = gets.chomp
puts "Please Enter Password"
get_password = gets.chomp
customer = Customer.find_by(
username: get_username,
password: get_password
)
if customer.nil? do
puts 'Sorry, username and/or password combination not valid. Please try again'
end
end
答案 2 :(得分:0)
只有一个错误会阻止您离开那里,在existing_user
函数中,您应该调用process_login
以外的login_screen_selection
。 login_screen_selection
仅发出一条消息并等待输入,如果收到输入,则程序结束。
def existing_user
puts "Please Enter Username"
get_username = gets.chomp
puts "Please Enter Password"
get_password = gets.chomp
customer = Customer.find_by(
username: get_username,
password: get_password
)
if customer.nil? do
puts 'Sorry, username and/or password combination not valid. Please try again'
process_login
end
end
答案 3 :(得分:0)
您可以进入循环。您将一直在那里直到找到客户。如果是这样,程序将继续运行,并显示菜单。
def existing_user
loop do
puts "Please Enter Username"
get_username = gets.chomp
puts "Please Enter Password"
get_password = gets.chomp
customer = Customer.find_by(
username: get_username,
password: get_password
)
break if customer
puts 'Sorry, username and/or password combination not valid. Please try again'
end
login_screen_selection
end