Robert Klemme
5/12/2005 11:33:00 AM
David A. Black wrote:
> HI --
>
> On Thu, 12 May 2005, Jens Riedel wrote:
>
>> Hello,
>>
>> I'm quite new to Ruby.
>> I'd to walk through a directory tree and edit all jsp files in there.
>>
>> I do it this way:
>>
>> def editDirectory(path)
>> Dir.entries(path).each { |filename|
>> next if filename =~ /^\.+$/
>> currFile = path + "/" + filename
>> if(File.stat(currFile).directory?)
>> editDirectory(currFile)
>> elsif(filename =~ /(.+)\.jsp$/)
>> # ... do something with the file
>> end
>> }
>> end
>>
>> I'd like to know if there is a more professional or more "ruby-like"
>> way to do this...
>
> You can use the 'find' module. Here's a parameterized version, which
> takes as its arguments a path and a file extension, and yields back
> the filenames it finds one by one:
>
> require 'find'
>
> def find_by_extension(path, ext)
> Find.find(path) do |f|
> next unless FileTest.file?(f)
> next unless /#{Regexp.escape(ext)}$/.match(f)
> yield f
> end
> end
>
> # Example of usage:
>
> find_by_extension("/home/dblack", ".rb") do |f|
> # do stuff with f
> end
>
>
> David
Even more generic:
module Find
def self.find_cond(dir, cond)
find(dir){|f| yield f if cond === f}
end
end
Find::find_cond ".", /\.jsp$/ do |f|
puts f
end
# and including the file type test
proper_test = Object.new
def proper_test.===(f) /\.jsp$/ =~ f and File.file? f end
Find::find_cond ".", proper_test do |f|
puts f
end
Hm, this might be worthwile to go into find.rb...
Kind regards
robert