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:

  1. what's right way break out of loop once i've found file contains data i'm looking for?

  2. 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

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -