From: Robert Klemme Date: 2004-04-10T00:09:13+09:00 Subject: Re: need help with recursion "David A. Black" schrieb im Newsbeitrag news:Pine.LNX.4.44.0404081823560.22274-100000@wobblini... > Hi -- > > On Fri, 9 Apr 2004, 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. > > I think it's because you're looking for a filename without the full > path. At least, if under_score.txt is one level down, I think that's > what's happening. You'd need to chdir to the new directory, which you > can do with Dir.chdir. > > You can actually let the Find module handle this too: > > class FileHandling > require 'find' > def noRecursiveUnderscore(dir) > Find.find(dir) do |f| > File.rename(f, f.gsub("_", " ")) if File.stat(f).file? > end > end > end There's a subtly problem with your code: Files which are in directories that contain an underscore are not treated well... Better do something along these lines: Dir[ File.join( dir, "**", "*" ) ].each do |name| d, base = File.split name changed = base.dup.gsub!("_", " ") and File.rename( name, File.join( d, changed ) ) end The same is possible with Find.find of course. In fact, File.find might be more efficient if the hieararchy contains many files. Kind regards robert