如何在Ruby中将用户输入与哈希中的键/值对进行比较?

如何在Ruby中将用户输入与哈希中的键/值对进行比较?,ruby,hash,Ruby,Hash,我正在制作一个非常简单的测验程序,其中问题是从散列随机生成的,用户输入答案。我很难将用户输入与特定的问题和答案键/值对进行比较。以下是迄今为止我采用的方法: def generate_question @questions = { "What is the capital of Japan?" => "Tokyo", "What is the capital of Portugal?" => "Lisbon" } keys = qu

我正在制作一个非常简单的测验程序,其中问题是从散列随机生成的,用户输入答案。我很难将用户输入与特定的问题和答案键/值对进行比较。以下是迄今为止我采用的方法:

  def generate_question
    @questions = {
      "What is the capital of Japan?" => "Tokyo",
      "What is the capital of Portugal?" => "Lisbon"
    }
    keys = questions.keys
    @question = keys[rand(keys.size)]
    puts @question
    response
  end
这只在50%的时间有效。例如,如果产生了“日本的首都是什么”的问题,那么有时“东京”是正确的,有时不是。如果有人能帮助我理解如何将用户的答案与哈希中正确的问题和答案值进行比较,我将不胜感激


谢谢大家!

发生这种情况是因为您正在迭代哈希。要解决此问题,请使用
@question
实例变量

def response
    puts "Please type your answer below"
    @answer = gets.chomp!
    correct_answer = @questions[@question]

    if correct_answer == @answer
        return "Well done, that's right!"
    else
        return "Not quite right have another go"
    end
end

你的问题就在这一部分

@questions.each do |question, answer|
  if question == @question && answer == @answer
    return "Well done, that's right!"
  else
    return "Not quite right have another go"
  end
end
如果第一个问题不是所问的问题,它将立即返回错误,而不看下一个问题,因为返回的是
方法
而不是块

即使它从区块返回,但它会说你错了,然后说你是对的(如果你正确回答了第二个问题)

要解决此问题,可以将其更改为

def response
  puts "Please type your answer below"
  @answer = gets.chomp!
  if @questions[@question].to_s.downcase == @answer.downcase
     "Well done, that's right!"
  else 
     "Not quite right have another go"
  end 
end

现在我们根据问题查找答案,并使答案不区分大小写

答案是否可以小写?尝试检查
answer.downcase==@answer.downcase
否,不起作用:(它总是正确地使用日本变量,但似乎从来没有将葡萄牙变量注册为正确的?关于这段代码,需要注意的一点是,您在可能不需要的时候使用了大量实例变量。实例变量会在对象的生命周期中持续存在,这意味着如果您不小心,它们会保留很长时间。请使用常规变量。)“局部”变量(例如,
questions
而不是
@questions
),除非您特别需要为其他方法调用保留该数据。谢谢您的提示@tadman!)
def response
  puts "Please type your answer below"
  @answer = gets.chomp!
  if @questions[@question].to_s.downcase == @answer.downcase
     "Well done, that's right!"
  else 
     "Not quite right have another go"
  end 
end