簡體   English   中英

Ruby塊似乎無法訪問局部作用域變量

[英]Ruby block cannot seem to access local scope variables

我正在寫一個函數,該函數讀一個答案鍵,創建一個問題,然后將正確答案與該問題相關聯。 這是我的功能:

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將被“重置”,此外,為什么在images塊中求值時answer_key.count將返回0? 我知道塊應該從調用它們的地方繼承本地作用域...為什么不傳遞answer_key的任何原因?

錯誤必須在其他地方,此代碼應該起作用。

編寫一些單元測試並重構此方法,它試圖做太多事情。

同樣,當您遍歷圖像時,可以擺脫counter而改用each_with_index

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM