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的任何原因?     
已邀请:
        错误必须在其他地方,此代码应该起作用。 编写一些单元测试并重构此方法,它正在尝试做很多事情。 同样,当您循环遍历图像时,可以摆脱
counter
,而改用
each_with_index
。     

要回复问题请先登录注册