1
我有兩個數組,一個是字符串,它們是問題,另一個是它的答案,它們也是字符串,數組的第一個位置的問題的答案也在第一個位置,但在第一個位置@answers,所有問題都是一樣的,所以我想要做的就是向用戶提問,如果他沒有回答預期的問題,他就要求再試一次。如何根據Ruby中某個索引所包含的值來比較數組?
這是我到目前爲止的代碼: 但我發現了以下錯誤:file_mng.rb:72:在block in play': undefined method
[]」爲無:NilClass(NoMethodError)
def play
arrange_arrays
#The method arrange_arrays fills the arrays @questions and @answers in
#a way that, the answer for the question in the first position of the
#array @questions is located also in the first position of the array @answers,
#so the index matches for the arrays.
puts
@questions.each_with_index do |question, i|
puts question
puts
puts "TYPE YOUR ANSWER"
puts
answer = gets.chomp
while answer != @answers[i]
puts
puts "INCORRECT, TRY AGAIN"
end
puts
puts "CORRECT !"
end
puts
puts "QUESTIONS ARE OVER, CONGRATULATIONS!"
end
def arrange_arrays
#everything located in a odd line is an question
#everything lcoated in an even line is an answer
File.open("questionary.out").each_line do |line|
i = i+1
if i % 2 == 0
@answers << line.to_s.downcase.chomp
else
@questions << line.to_s.downcase.chomp
end
end
end
感謝一百萬讀這個。
這太奇怪了,因爲當我從play方法內部打印兩個數組時,它會將它們打印爲實際值而不是空的,我只是在我的問題中添加了arrange_arrays,如果你介意給它看: ) –
'arrange_arrays'不會像寫入那樣工作。如果你還沒有初始化'i',你就不能'i = i + 1'。事實上它沒有提出錯誤,這表明我不會輸入'each_line'塊,儘管我不能說明這一點。 –
抱歉,我錯過了將代碼複製到堆棧溢出時的i變量初始化(i = 0),並且我確信該方法有效,因爲當我打印數組時,它們充滿了來自文件的數據,這就是認爲讓我感到困惑 –