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

时间:2019-06-07 17:54:33

标签: ruby hash

我正在制作一个非常简单的测验程序,其中从哈希中随机生成问题,然后用户输入答案。我正在努力将用户输入与特定的问题和答案键/值对进行比较。这是我到目前为止的方法:

  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
  def response
    puts "Please type your answer below"
    @answer = gets.chomp!
    @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
  end

这仅在50%的时间内有效。例如,如果问题“日本的首都是什么?”是生成的,有时“东京”是正确的,有时则不是。如果有人能帮助我了解如何将用户的答案与正确的问题和哈希值进行比较,将不胜感激?

谢谢!

2 个答案:

答案 0 :(得分:3)

之所以发生这种情况,是因为您正在遍历哈希。要解决此问题,请使用@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

答案 1 :(得分:1)

您要为此部分发行

@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

如果第一个问题不是所要提问的问题,它将立即返回您错了,而无需查看下一个问题,因为返回是从method而不是块返回的。

即使它从代码块返回,尽管它会说您错了,然后说您是对的(如果您正确回答了第二个问题)。

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

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

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