0

きみならどうする?スタイルのプログラムを書いています。私は3つの質問配列を作成しています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}

しかし、その時点では、どちらq2q3定義されていません。それらを参照する前に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 に答える