I’m writing a choose-your-own-adventure style program. I’m creating three question arrays q1—q3, each with an array, another array, and a hash. The goal is to move through the array with my question_charge method then return what the next question array should be based on the user’s answer.
puts "Please choose an answer to the following questions"
q1 = [["What is your answer to this very first question?"],["A - Option 1","B - Option 2","C - Option 3"],{"A" => q2,"B" => q3, "C" => q3}]
q2 = [["This is the second question, can I have an answer?"],["A - Option 2-1","B - Option 2-2","C - Option 2-3"],{"A" => q3,"B" => q3,"C" => q4}]
q3 = [["Question #3! What is your answer?"],["A - Option 3-1","B - Option 3-2","C - Option 3-3"]]
current_question = q1
def question_charge(current_question)
x = 0
puts current_question[x]
x += 1
puts current_question[x]
answer = gets.chomp
puts "You answered " + answer
x += 1
current_question = current_question[x][answer]
end
question_charge(current_question)
Sometimes when I run this, I receive the following error:
(eval):2: undefined local variable or method `q2' for main:Object (NameError)
When it does work, q3 doesn’t have a hash in the array as in the final question. When I answer 'A' to the first question, it returns all of my arrays multiple times. If I answer 'C' for q3, it returns just fine. Can anyone tell me how I can return the only the array I want and without receiving an error?
When you are defining the first question, your hash is the following:
but at that point, neither
q2orq3are defined. You need to defineq2andq3before you reference them.