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