我试图获得一些东西,如果有人输入一个字符串,它验证它并运行另一个功能。我的问题是它结束程序而不是运行其他功能。 这是我的代码:
puts "redirecting to login"
def login()
puts ""
print "Username: "
username = gets.chomp
checkusername()
end
def password()
print "Password: "
passwordconf = gets.chomp
checkpassword()
end
def success()
puts "You're logged in!"
loop { sleep 10 }
end
def checkusername()
if username == name
password()
else
login()
end
end
def checkpassword()
if passwordconf == password
success()
else
login()
end
end
login()
loop { sleep 10 }
当登录正在运行时,我输入我想要检查的字符串的获取,当我按Enter键运行checkusername时,程序结束,即使它是正确的。
登录函数在输入字符串后运行checkusername函数,然后按Enter键。我的问题是,一旦发生这种情况,程序就会终止,而不是重定向回登录功能或密码功能。我试图找出不会发生的事情。
错误输出:
Traceback (most recent call last):
2: from blank.rb:41:in `<main>'
1: from blank.rb:16:in `login'
blank.rb:28:in `checkusername': undefined local variable or method `username' for main:Object (NameError)
我是Ruby的初学者,我花了很多时间让它工作,但我无法做到。谢谢!
答案 0 :(得分:2)
puts 'redirecting to login'
def login
puts # You do not need the quotes just to put an empty line
print 'Username: '
username = gets.chomp
check_username username # I recommend using snake_case for variable names and method names
end
def password
print 'Password: '
password_conf = gets.chomp
check_password password_conf
end
def success # With Ruby you do not need the empty ()
puts "You're logged in!"
end
def check_username(username)
name = 'random'
username == name ? password : login # This is a if/else statement on one line
end
def check_password(password_conf)
password = 'password'
password_conf == password ? success : login # You also don't need the () for calling a method either
end
login
loop { sleep 10 } # This will keep the program running forever, you should probably remove this line
我对您的代码进行了一些更改,上面有一些评论。
非全局变量(应该避免使用全局变量)需要传递给方法以供使用。这是程序崩溃的主要原因。您要求checkusername
方法在login
方法中使用变量,由于除非您传递变量,否则方法不会共享变量。
同样,我会尽可能避免全局变量。
答案 1 :(得分:0)
您收到错误消息,因为username
功能中checkusername()
未知。据说超出了范围。在login()
函数之外不知道。这是一个局部变量。它的范围是login()
的本地范围。
解决此问题的一种方法是将变量声明为全局。这意味着它将具有全球范围,并且可以从程序的任何位置获得。要将变量声明为全局变量,请使用$
前缀。
username = gets.chomp
变为$username = gets.chomp
。然后,当您想再次引用它时,使用相同的前缀:if $username == name...
Difference between various variables scopes in ruby
http://ruby-for-beginners.rubymonstas.org/writing_methods/scopes.html
(编辑!正如Sergio Tulentsev在下面所说,全局变量通常是一个坏主意。https://www.thoughtco.com/global-variables-2908384)