2013-10-20 104 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)