polm23
polm23

Reputation: 15593

File read loop with early exit

I have to deal with some unwieldy files in Ruby. Given a particular ID, I know the data associated with the ID will be in not more than one of the files, but I'm not sure which one. It may also be absent, which is an error state I need to handle. So I have a loop like this:

files = ['a','b','c','d']
files.each do |filename|
  File.open(filename,'r') do |f|
    break unless contains_id(myid)
    do_stuff
  end
end

So I have two questions:

  1. What's the right way to break out of the loop once I've found the file that contains the data I'm looking for?

  2. How can I deal with the situation where the data is not in any file?

This is what I came up with but it feels rough:

files = ['a','b','c','d']
found = false
files.each do |filename|
  break if found
  File.open(filename,'r') do |f|
    break unless contains_id(myid)
    found = true
    do_stuff
  end
end
do_error_stuff unless found

Upvotes: 1

Views: 103

Answers (1)

Stuart M
Stuart M

Reputation: 11588

You can use Enumerable#find instead of #each to find the first entry in files for which the block returns true, or else nil. So this would look like:

files = ['a','b','c','d']
file = files.find do |filename|
  File.open(filename,'r') do |f|
    contains_id(myid)
  end
end
do_error_stuff unless file

Upvotes: 3

Related Questions