0

I'm writing a function that reads in an answer key, creates a question, and then associates the right answer with that questions. Here's my function:

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

and here's a snippet of the output right before it enters the images.each block.

before entering: D

before entering: A

before entering: A

before entering: C

before entering: A

found key

---------Answer is:--------

answer is nil

Does anyone know why answer_key would "reset", and, furthermore, why answer_key.count would return 0 when evaluated within the images block? I understand that blocks should inherit the local scope from where they are called...any reason why answer_key would not be passed?

2
  • 1
    Are you sure this is the complete code you're running? There is no reason why within the block you showed to us it should be "reset" at all. Commented Jun 25, 2011 at 9:18
  • Does the 'puts "number #{num} is #{answer.to_s}"' line output several times? Commented Jun 25, 2011 at 10:10

1 Answer 1

3

The mistake must be somewhere else, this code should work.

Write a few unit tests and refactor this method, it's trying to do too many things.

Also, when you loop over the images, you can get rid of counter and use each_with_index instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Yea, it seems like that's the issue. Just found out the code runs fine on one of my friend's computers but not on mine. We have the same version of ruby and rails installed as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.