我正在编写一个选择您自己的冒险风格的程序。我正在创建三个问题数组q1
—q3
,每个都有一个数组,另一个数组和一个散列。目标是使用我的question_charge
方法遍历数组,然后根据用户的答案返回下一个问题数组。
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)
有时当我运行这个,我收到以下错误:
(eval):2: undefined local variable or method `q2' for main:Object (NameError)
当它工作时,q3
在数组中没有哈希值,就像最后一个问题一样。当我对第一个问题回答'A'
时,它多次返回我的所有数组。如果我回答'C'
为q3
,它返回很好。谁能告诉我如何才能返回我想要的唯一数组,而不会收到一个错误?
当您定义第一个问题时,您的散列如下:
{"A" => q2,"B" => q3, "C" => q3}
,但此时q2
和q3
都没有定义。您需要在引用q2
和q3
之前定义它们。
我会试着重写你的方法让它更有意义
def ask_question(current_question)
question, options, next_question_hash = current_question
puts question # "What is your answer to this very first question?"
puts options # "A - Option 1", ...
answer = gets.chomp
puts "You answer #{answer}"
next_question = next_question_hash[answer]
end
这将提出一个问题,然后返回下一个要回答的问题。