I am making a really simple quiz program where questions are randomly generated from a hash and the user inputs their answer. I am struggling to compare the user input to a specific question and answer key/value pair. Here are the methods I have so far:
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
This only works 50% of the time. For example, if the question 'What is the capital of Japan?' is generated, sometimes 'Tokyo' is correct and sometimes it isn't. Would be really grateful if anyone could help me understand how to compare the user's answer to the right question and answer value in the hash?
Thank you !