From: David Alan Black Date: 2004-04-09T10:44:16+09:00 Subject: Re: need help with recursion Hi -- Mark Hubbart writes: > On Apr 8, 2004, at 5:54 PM, Boris "BXS" Schulz wrote: > > > Hi, > > > > I was just trying to replace the underscores I get when using files > > from my Linux-friends, but somehow my code seems to be corrupt. > > The code runs fine without the recursion, so it must be something > > wrong in those three lines, but I do not know what :-( > > The "under_score.txt" is my testobject. > > I am using: Ruby 1.8.0, Windows XP > > Any help would be great. > > > > greetings, BXS > > > > > > This is my code: > > > > class FileHandling > > def noRecursiveUnderscore(basedirectory) > > Dir::foreach(basedirectory){ |filename| > > if File.stat(filename).file? > > newname = filename.gsub("_", " ") > > File.rename(filename, newname) > > end > > if File.stat(filename).directory? and filename != "." and filename > > != ".." > > noRecursiveUnderscore(filename) > > end > > } > > end > > > > end #class > > > > testDir = FileHandling.new() > > testDir.noRecursiveUnderscore(Dir.getwd) > > > > > > **** This is my errormessage **** > > recursivenounderscore.rb:4:in `stat': No such file or directory - > > under_score.txt > > (Errno::ENOENT) > > [...] > > You are correct, the problem *is* in the recursion part; you are > stat()ing the same filename "with_underscores", but you had already > renamed the file, so it gave an error. To fix it, make it an > if..elsif..end, rather than two if..end's: > > if File.stat(filename).file? > newname = filename.gsub("_", " ") > File.rename(filename, newname) > elsif File.stat(filename).directory? and filename != "." and filename > != ".." > noRecursiveUnderscore(filename) > end 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. David -- David Alan Black home: dblack@wobblini.net # New email address work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav