如何让程序检查密钥是否与值“相等”?

时间:2013-10-20 17:19:36

标签: ruby key-value

我试图写一个简单的用户名/密码提示。我还是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中的用户名之前收到一个奇怪的错误。

1 个答案:

答案 0 :(得分: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)