我在寫一個函數,它讀入一個答案關鍵字,創建一個問題,然後將正確答案與該問題相關聯。這裏是我的功能:Ruby塊似乎無法訪問本地作用域變量
def self.save_images_in_dir(dir)
answer_key_file = Dir.glob(dir+"/*.{rtf,txt}").first
answer_key = Array.new
if answer_key_file
puts "found key"
File.open(answer_key_file, "r") do |infile|
while (line = infile.gets)
if line.match(/^\d+[.]\s+/)
num = line.match(/\d+/)
answer = line.gsub(/\d+[.]\s+/,"") # Take out the 1.
answer.chomp!
answer_key.push(answer.to_s)#answer_key[num.to_s]=answer.to_s
puts "number #{num} is #{answer.to_s}"
end
end
end
end
images = Dir.glob("#{dir}*.{png,jpeg,jpg,gif}").sort_by {|file| File.ctime(file) }
counter = 0
answer_key.each do |q|
puts "before entering: #{q}"
end
images.each do |img|
q = self.new
q.tags = get_tags(img)
q.correct_answer = answer_key[counter]
puts "---------Answer is:#{answer_key[counter]}--------\n"
q.photo = File.open(img)
if q.correct_answer.nil?
puts "answer is nil"
end
counter = counter + 1
end
end
這裏有一個片段的輸出之前,它進入images.each塊。
在進入之前:d
在進入之前:甲
在進入之前:進入
之前:C
在進入之前:甲
發現鍵
---------答案是:--------
答案是零
有誰知道爲什麼會answer_key「復位」,此外,爲什麼當在圖像中評估阻塞answer_key.count將返回0?我知道塊應該從它們被調用的地方繼承本地作用域...... answer_key不會被傳遞的任何原因?
您確定這是您正在運行的完整代碼嗎?沒有任何理由說明你向我們展示的應該是「重置」。 – Howard
'puts'number#{num}是否是#{answer.to_s}''行輸出的幾次? – Pavling