0

我正在编写一个选择你自己的冒险风格的程序。我正在创建三个问题数组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它返回就好了。谁能告诉我如何返回我想要的唯一数组而不会收到错误?

4

2 回答 2

0

当您定义第一个问题时,您的哈希值如下:

{"A" => q2,"B" => q3, "C" => q3}

但在这一点上,既没有q2或也没有q3被定义。您需要在引用它们之前定义q2和。q3

于 2013-01-19T16:47:20.563 回答
0

我会尝试重写你的方法以使其更有意义

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

这会提出一个问题,然后返回下一个要回答的问题。

于 2013-01-19T16:48:55.737 回答