From: Chris White Date: 2011-08-20T06:06:20+09:00 Subject: Re: Searching in a directory On Aug 19, 2011, at 1:51 PM, Yu Yu wrote: > This search-routine is part of a bigger script and I've problems with > this part. I try to keep it simple... > > I'm looking for one string: dog > > in all these files: > > file 1: > cat bird > frog eagle > > file2: > dog cat > eagle frog > > file3: > cat cat > eagle bird > dog bird > > file4: > ... > > The search begins in file1. If the string dog is found in file2 the > search should stop. Thats all! Ah, here's a way to do that: dir_path = './test_files' str = "dog" Dir.chdir(dir_path) do Dir.glob("*.txt").inject(false) do |found, filename| IO.foreach(filename) do |line| if line =~ /#{str}/ puts "#{filename}: #{str}" if found == true puts "Second instance found" exit # or however you want to handle this else found = true end end end found end end This exits as soon as the second match is found, but you could have it run a method or something like that instead. You can also use throw/catch (note this is not about exceptions as with other languages using try/catch, it's meant to break out of deeply nested loops) to break out of the loop and go elsewhere. Regards, Chris White http://www.twitter.com/cwgem