From: "David A. Black" Date: 2004-04-09T20:09:59+09:00 Subject: Re: need help with recursion Hi -- On Fri, 9 Apr 2004, ibotty wrote: > > You'll still have the subdirectory problem. Let's say you've got: > > > > a > > a/b > > a/b/under_score.txt > > > > It will run the method for b, and filename will be set to > > under_score.txt. But when it stats it, it will stat it with respect > > to a, unless you do a chdir to b or expand the path. > > you can of course simply set filename to the right value. just change this, > and it should work. > > File.rename(filename, newname) > + filename = newname > end That won't change the behavior of the original code. The problem I'm describing is that you're trying to stat a file when you're in the wrong directory. It's not the same as the problem involving renaming the file. Here's an example, leaving out the renaming to show the problem: def find_files_broken(dir) Dir.new(dir).reject {|f| /\A\.\.?\z/.match(f)} .each do |f| if File.stat(f).file? puts "File: #{f}" elsif File.stat(f).directory? puts "Directory: #{f}" find_files(f) end end end find_files_broken(Dir.pwd) Here's a modified example that works: def find_files(dir) Dir.chdir(dir) do Dir["*"].each do |f| if File.stat(f).file? puts "File: #{f}" elsif File.stat(f).directory? puts "Directory: #{f}" find_files(f) end end end end find_files(Dir.pwd) The difference is that I've used Dir.chdir to make sure I'm addressing the right space at the right time. (This also allows me to use Dir.[] instead of Dir.new, which saves the trouble of checking for "." and "..".) David -- David A. Black dblack@wobblini.net