ruby - File read loop with early exit -
i have deal unwieldy files in ruby. given particular id, know data associated id in not more one of files, i'm not sure one. may absent, error state need handle. have loop this:
files = ['a','b','c','d'] files.each |filename| file.open(filename,'r') |f| break unless contains_id(myid) do_stuff end end
so have 2 questions:
what's right way break out of loop once i've found file contains data i'm looking for?
how can deal situation data not in file?
this came feels rough:
files = ['a','b','c','d'] found = false files.each |filename| break if found file.open(filename,'r') |f| break unless contains_id(myid) found = true do_stuff end end do_error_stuff unless found
you can use enumerable#find
instead of #each
find first entry in files
block returns true, or else nil
. like:
files = ['a','b','c','d'] file = files.find |filename| file.open(filename,'r') |f| contains_id(myid) end end do_error_stuff unless file
Comments
Post a Comment