为什么我的方法返回我的所有数组?

时间:2013-01-19 16:40:04

标签: ruby hash methods multidimensional-array

我正在写一个选择你自己的冒险风格的程序。我正在创建三个问题数组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,则返回正常。谁能告诉我如何才能返回我想要的唯一数组并且没有收到错误?

2 个答案:

答案 0 :(得分:0)

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

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

但此时,q2q3均未定义。在引用它们之前,您需要定义q2q3

答案 1 :(得分: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

这会问一个问题,然后返回下一个问题来回答。