gpt4 book ai didi

ruby - 如何将用户输入与 Ruby 中散列中的键/值对进行比较?

转载 作者:数据小太阳 更新时间:2023-10-29 07:54:44 25 4
gpt4 key购买 nike

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

  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% 的时间有效。例如,如果问题“日本的首都是哪里?”生成时,有时“Tokyo”是正确的,有时则不是。如果有人能帮助我理解如何将用户的答案与哈希中正确的问题和答案值进行比较,我将非常感激?

谢谢!

最佳答案

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

关于ruby - 如何将用户输入与 Ruby 中散列中的键/值对进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56499164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com