2013-10-20 76 views
0

我试图写一个简单的用户名/密码提示。我仍然是Ruby的初学者。如何让程序检查密钥是否与该值相等?

combo = Hash.new 
combo["placidlake234"] = "tastychicken" 
combo["xxxdarkmasterxxx"] = "pieisgood" 
combo["dvpshared"] = "ilikepie" 

puts "Enter your username." 
username = gets.chomp 

def user_check 
    if username = ["placidlake234"||"xxxdarkmasterxxx"||"dvpshared"] 
    puts "What is your password?" 
    password = gets.chomp 
    pass_check 
    else 
    puts "Your username is incorrect." 
    end 
end 

def pass_check 
    if password => username 
    puts "You have signed into #{username}'s account." 
    end 
end 

user_check() 

当我尝试运行它时,我在=> username的用户名之前发现了一个奇怪的错误。

+0

什么是错误注释掉? –

+0

有几个问题:1.不使用组合; 2. [“placidlake234”|| “xxxdarkmasterxxx”|| “dvpshared”] => [“placidlake234”],所以你有if username = [“placidlake234”],这是if [“placidlake234”],因为你错误地使用=而不是==; 3.你需要def passcheck(密码,用户名),以使passcheck()访问这些变量; 4.你需要密码==用户名(不是=>); 5.坚持认为密码与用户名相同是不常见的做法; 6.您需要user_check的user_check(用户名)才能访问用户名。你有StrangeRuntimeError? –

+0

如果您正在使用Ruby on Rails,则Devise模块将自动执行用户名/密码检查。 –

回答

0

有,应当予以纠正几件事情:
我在下面

combo = Hash.new 
combo["placidlake234"] = "tastychicken" 
combo["xxxdarkmasterxxx"] = "pieisgood" 
combo["dvpshared"] = "ilikepie" 

puts "Enter your username." 
username = gets.chomp 

def user_check(username, combo) 
    #HERE combo.keys gives keys. 
    if combo.keys.include? username 
    puts "What is your password?" 
    password = gets.chomp 
    if pass_check(username, password, combo) 
     puts "You have signed into #{username}'s account." 
    else 
     puts "Wrong password, sorrie" 
    end 
    else 
    puts "Your username is incorrect." 
    end 
end 

def pass_check(username, password, combo) 
    #Here, access by combo[username] 
    return true if password == combo[username] 
    false 
end 

#HERE, pass the arguments, so that it is available in function scope 
user_check(username, combo)