From: RichardOnRails Date: 2007-12-05T14:45:45+09:00 Subject: Re: Rubyisms wanted to shorten code in search program On Dec 4, 11:07 am, Robert Klemme wrote: > 2007/12/4, RichardOnRails : > > > > > Hi, > > > Search on WindowsXP/SP2 didn't seem to locate a file is looking for. > > As someone relatively new to Ruby, I wonder whether there are any > > Rubyisms I could have used to cut down the the 80+ lines I took to > > accomplish this task, given the USAGE requirement I posed in the > > code. > > > Thanks in Advance, > > Richard > > > # Search.rb > > # K:/_Projects/Ruby/_Ruby_Tests/TestSearchDir/SearchWithArgs > > > # USAGE: Search.rb -d DirPath [-f regexpFileNameSought] [-t > > regexpTextSought] > > Just a quick hack without command line processing. > > dir = ... > name_regexp = ... # may be null > content_regexp = ... # may be null > > require 'find' > > Find.find dir do |file| > path, base = File.split file > next if name_regexp && name_regexp !~ base or > content_regexp && context_regexp !~ File.read(file) > puts file > end > > For command line processing I'd use OptionParser. > > Kind regards > > robert Hi Robert, Your algorithm's concept is excellent ... just what I hoped to learn in order to escape my procedural-programming heritage and start to code like a Rubyist. > OptionParser Thanks for that reference. I'll look into it. Just for the record, I had to tweak your code to get your concept working. I thought of it as "earning my keep." Below is my test code. Again, thanks for your guidance. Best wishes, Richard dir = 'K:/_Projects/Ruby/_Ruby_Tests' name_regexp = nil # may be null content_regexp = Regexp.new('curArg') # may be null require 'find' Find.find dir do |file| path, base = File.split file next if name_regexp && name_regexp !~ base or content_regexp && (!File.file?(file) || File.read(file) !~ content_regexp) puts file end