Ruby block cannot seem to access local scope variables
I'm writing a function that reads in an answer key, creates a question, and then associates the right answer with that questions. Here's my function:
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[coun开发者_运维问答ter]
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
and here's a snippet of the output right before it enters the images.each block.
before entering: D
before entering: A
before entering: A
before entering: C
before entering: A
found key
---------Answer is:--------
answer is nil
Does anyone know why answer_key would "reset", and, furthermore, why answer_key.count would return 0 when evaluated within the images block? I understand that blocks should inherit the local scope from where they are called...any reason why answer_key would not be passed?
The mistake must be somewhere else, this code should work.
Write a few unit tests and refactor this method, it's trying to do too many things.
Also, when you loop over the images, you can get rid of counter
and use each_with_index
instead.
精彩评论