Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Ruby块似乎无法访问本地作用域变量_Ruby On Rails_Ruby_Scope_Block - Fatal编程技术网

Ruby on rails Ruby块似乎无法访问本地作用域变量

Ruby on rails Ruby块似乎无法访问本地作用域变量,ruby-on-rails,ruby,scope,block,Ruby On Rails,Ruby,Scope,Block,我正在编写一个函数,它读入一个答案键,创建一个问题,然后将正确答案与该问题关联起来。以下是我的功能: 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 |infi

我正在编写一个函数,它读入一个答案键,创建一个问题,然后将正确答案与该问题关联起来。以下是我的功能:

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
这是输入图像前的输出片段。每个块

进入前:D

进入前:A

进入前:A

进入前:C

进入前:A

找到钥匙

---------答案是:--------

答案是零


有人知道为什么answer_key会“重置”,而且answer_key.count在图像块中求值时会返回0吗?我知道块应该从调用它们的地方继承本地作用域…有没有任何原因可以解释为什么不会传递应答键?

错误一定在其他地方,此代码应该可以工作

编写一些单元测试并重构这个方法,它试图做的事情太多了


此外,当您在图像上循环时,您可以去掉
计数器
,而使用
每个带有索引的

错误一定在其他地方,此代码应该可以工作

编写一些单元测试并重构这个方法,它试图做的事情太多了


此外,当您在图像上循环时,您可以去掉
计数器
,而使用
每个_和_索引

您确定这是您正在运行的完整代码吗?在您向我们展示的块中,没有理由认为它应该是“重置”的。puts数#{num}是否是#{answer.to_s}行输出多次?您确定这是您正在运行的完整代码吗?在您向我们展示的块中,没有理由认为它应该是“重置”的。puts数#{num}是否是#{answer.to#s}行输出多次?是的,似乎这就是问题所在。刚发现代码在我朋友的一台电脑上运行良好,但在我的电脑上运行不好。我们也安装了相同版本的ruby和rails。是的,这似乎就是问题所在。刚发现代码在我朋友的一台电脑上运行良好,但在我的电脑上运行不好。我们也安装了相同版本的ruby和rails。