Other answers have answered the question given in the title of your question.
I would like to suggest that you consider adopting some variation of the following code.
def get_answer(question, answers)
choices_to_answers = construct_choices_to_answers(answers)
loop do
puts "#{question}"
display_choices(choices_to_answers)
print "answer: "
choice = gets.chomp
puts choice
break choices_to_answers[choice] if choices_to_answers.key?(choice)
puts "\nThat answer is invalid."
puts "Enter a letter between 'a' and '#{choices_to_answers.keys.last}'\n"
end
end
def construct_choices_to_answers(answers)
('a'..('a'.ord + answers.size - 1).chr).to_a.zip(answers).to_h
end
def display_choices(choices_to_answers)
choices_to_answers.each { |k,v| puts "(#{k}): #{v}" }
end
Suppose the possible answers were as follows.
answers = %w| Y R Z Q |
#=> ["Y", "R", "Z", "Q"]
Then
choices_to_answers = construct_choices_to_answers(answers)
#=> {"a"=>"Y", "b"=>"R", "c"=>"Z", "d"=>"Q"}
and
display_choices(choices_to_answers)
prints
(a): Y
(b): R
(c): Z
(d): Q
Here I've assumed that the choices are always consecutive letters beginning with "a". If that assumption is correct there is no need to manually associate those letters with the possible answers.
Let me now show a possible conversation with the method (with answers as defined above).
question = "What is the last letter in the alphabet?"
get_answer(question, answers)
#=> "R"
The following is displayed.
What is the last letter in the alphabet?
(a): Y
(b): R
(c): Z
(d): Q
answer: e
That answer is invalid.
Enter a letter between 'a' and 'd'
What is the last letter in the alphabet?
(a): Y
(b): R
(c): Z
(d): Q
answer: b
You might then construct an array of hashes that provide the question, possible answers, correct answer, possibly the weight of the question and a boolean indicating whether a correct answer was given.
questions = [
...
{ question: "What is the last letter in the alphabet?",
answers: ["Y", "R", "Z", "Q"],
correct_answer: "Z",
weight: 1,
correct_answer_given: nil
},
...
]
The value of :correct_answer_given for each question is updated to true or false when the question is answered. Once all questions have been answered questions can be used to determine a mark for the exam.
If you wish to assign a number to each question you could write
question_number = 0
questions.each do |h|
question_number += 1
g = h.merge(question: "#{question_number}. #{h[:question]}")
answer = get_answer(question, g[:answers])
h[:correct_answer_given] = h[:correct_answer] == answer
end
If question_number #=> 12 and
h[:question]
#=> "What is the last letter in the alphabet?",
then
g[:question]
#=> "12. What is the last letter in the alphabet?"