How to compare user input to key/value pair in hash in Ruby?

Viewed 289

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 !

2 Answers

This is occuring because you are iterating through the hash. To fix this, use the @question instance variable.

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

Your issue it this part

@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

If the first question is not the question that was asked it will immediately return that you are wrong without looking at the next question because the return returns from the method not from the block.

Even if it returned from the block though it would say you were wrong and then say you were right (if you answered the second question correctly).

To solve this you can change it to

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

Now we are looking up the answer based on the question and making the answer case insensitive

Related