2011-06-25 72 views
0

我在写一个函数,它读入一个答案关键字,创建一个问题,然后将正确答案与该问题相关联。这里是我的功能: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不会被传递的任何原因?

+1

您确定这是您正在运行的完整代码吗?没有任何理由说明你向我们展示的应该是“重置”。 – Howard

+0

'puts'number#{num}是否是#{answer.to_s}''行输出的几次? – Pavling

回答

3

错误必须在别的地方,这段代码应该可以工作。

编写几个单元测试并重构此方法,它试图做太多事情。

此外,当您循环显示图像时,您可以删除counter并使用each_with_index代替。

+0

是的,这似乎是这个问题。只是发现代码在朋友的一台计算机上运行良好,但没有运行在我的计算机上。我们也安装了相同版本的ruby和rails。 – kikster