From: RichardOnRails Date: 2007-12-06T05:04:59+09:00 Subject: Re: Rubyisms wanted to shorten code in search program On Dec 5, 3:21 am, Robert Klemme wrote: > 2007/12/5, RichardOnRails : > > > > > 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. > > Oh, yes. Sorry for that. But then again, you should probably globally > "next" if it is not a file because otherwise the name regexp will also > match directories and behavior is a bit inconsistent. > > Kind regards > > robert > > -- > use.inject do |as, often| as.you_can - without end Hi Robert, > Oh, yes. Sorry for that. Please, no apologies. Your few words of insight were worth everything. It's our obligation to work out the details, not yours! > you should probably globally "next" if it is not a file ... Thanks for that additional observation. I only superficially tested the code to confirm that it found the files I expected in my original search. Again, thank you for taking the time to offer your guidance. Best wishes, Richard