# Need help with recursion

**URL:** <https://rubytalk.org/t/need-help-with-recursion/10945>\
**Category:** ruby-talk\
**Created:** [9 April 2004 00:54 UTC](https://rubytalk.org/t/need-help-with-recursion/10945 "2004-04-09T00:54:16Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![Boris\_BXS\_Schulz](https://avatars.discourse-cdn.com/v4/letter/b/ce73a5/32.png) [@Boris\_BXS\_Schulz](https://rubytalk.org/u/Boris_BXS_Schulz)\
**Post date:** [9 April 2004 00:54 UTC](https://rubytalk.org/t/need-help-with-recursion/10945/1 "2004-04-09T00:54:16Z")

</div>

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) from recursivenounderscore.rb:4:in`noRecursiveUnderscore’  
from recursivenounderscore.rb:3:in `foreach' from recursivenounderscore.rb:3:in`noRecursiveUnderscore’  
from recursivenounderscore.rb:9:in `noRecursiveUnderscore' from recursivenounderscore.rb:3:in`foreach’  
from recursivenounderscore.rb:3:in `noRecursiveUnderscore’  
from recursivenounderscore.rb:17

---

<div class="post-metadata">

**Author:** ![Mark\_Hubbart](https://avatars.discourse-cdn.com/v4/letter/m/b77776/32.png) [@Mark\_Hubbart](https://rubytalk.org/u/Mark_Hubbart)\
**Post date:** [9 April 2004 01:26 UTC](https://rubytalk.org/t/need-help-with-recursion/10945/2 "2004-04-09T01:26:43Z")

</div>

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

That should fix that particular problem.

–Mark

> **···**
>
> 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)  
> > […]

---

<div class="post-metadata">

**Author:** ![David\_A\_Black3](https://avatars.discourse-cdn.com/v4/letter/d/6a8cbe/32.png) [@David\_A\_Black3](https://rubytalk.org/u/David_A_Black3)\
**Post date:** [9 April 2004 01:33 UTC](https://rubytalk.org/t/need-help-with-recursion/10945/3 "2004-04-09T01:33:13Z")

</div>

Hi --

> 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:

&nbsp;&nbsp;class FileHandling  
&nbsp;&nbsp;&nbsp;&nbsp;require 'find'  
&nbsp;&nbsp;&nbsp;&nbsp;def noRecursiveUnderscore(dir)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Find.find(dir) do |f|  
&nbsp;&nbsp;File.rename(f, f.gsub("\_", " ")) if File.stat(f).file?  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end

David

> **···**
>
> On Fri, 9 Apr 2004, Boris "BXS" Schulz wrote:
> 
> --  
> David A. Black  
> dblack@wobblini.net

---

<div class="post-metadata">

**Author:** ![David\_Alan\_Black2](https://avatars.discourse-cdn.com/v4/letter/d/5f9b8f/32.png) [@David\_Alan\_Black2](https://rubytalk.org/u/David_Alan_Black2)\
**Post date:** [9 April 2004 01:44 UTC](https://rubytalk.org/t/need-help-with-recursion/10945/4 "2004-04-09T01:44:16Z")

</div>

Hi –

Mark Hubbart [discord@mac.com](mailto:discord@mac.com) writes:

> > 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

> **···**
>
> > On Apr 8, 2004, at 5:54 PM, Boris “BXS” Schulz wrote:
> 
> –  
> David Alan Black  
> home: [dblack@wobblini.net](mailto:dblack@wobblini.net) # New email address  
> work: blackdav@shu.edu  
> Web: [http://pirate.shu.edu/~blackdav](http://pirate.shu.edu/~blackdav)

---

<div class="post-metadata">

**Author:** ![Robert](https://avatars.discourse-cdn.com/v4/letter/r/e95f7d/32.png) [@Robert](https://rubytalk.org/u/Robert)\
**Post date:** [9 April 2004 15:09 UTC](https://rubytalk.org/t/need-help-with-recursion/10945/5 "2004-04-09T15:09:13Z")

</div>

“David A. Black” [dblack@wobblini.net](mailto:dblack@wobblini.net) schrieb im Newsbeitrag  
news:Pine.LNX.4.44.0404081823560.22274-100000@wobblini…

> Hi –
> 
> > 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

```

> **···**
>
> > On Fri, 9 Apr 2004, Boris “BXS” Schulz wrote:

---

<div class="post-metadata">

**Author:** ![ibotty](https://avatars.discourse-cdn.com/v4/letter/i/4af34b/32.png) [@ibotty](https://rubytalk.org/u/ibotty)\
**Post date:** [9 April 2004 10:19 UTC](https://rubytalk.org/t/need-help-with-recursion/10945/6 "2004-04-09T10:19:15Z")

</div>

> 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

hope, i understood you.

~ibotty

---

<div class="post-metadata">

**Author:** ![David\_A\_Black3](https://avatars.discourse-cdn.com/v4/letter/d/6a8cbe/32.png) [@David\_A\_Black3](https://rubytalk.org/u/David_A_Black3)\
**Post date:** [9 April 2004 15:58 UTC](https://rubytalk.org/t/need-help-with-recursion/10945/7 "2004-04-09T15:58:09Z")

</div>

Hi --

> Dir[File.join( dir, "\*\*", "\*" )].each do |name|  
> &nbsp;&nbsp;d, base = File.split name  
> &nbsp;&nbsp;changed = base.dup.gsub!("\_", " ") and  
> &nbsp;&nbsp;&nbsp;&nbsp;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.

Yes, actually I used Find.find in my example 🙂 You're right about  
the overzealous gsub'ing. I'm not sure how directories were supposed  
to be handled, but I thought I was ignoring them, which I accidentally  
wasn't.

But here's some rename weirdness I've discovered while doing this:

&nbsp;&nbsp;$ ls u\_score/  
&nbsp;&nbsp;u\_file  
&nbsp;&nbsp;$ ruby -e 'File.rename("u\_score/u\_s", "u\_score/u s")'  
&nbsp;&nbsp;-e:1:in `rename': No such file or directory -  
&nbsp;&nbsp;u\_score/u\_s or u\_score/u s (Errno::ENOENT)  
&nbsp;&nbsp;&nbsp;&nbsp;from -e:1

I have to admit I have no idea why that happens or even what the error  
exactly means. (What's with the "or"?)

David

> **···**
>
> On Sat, 10 Apr 2004, Robert Klemme wrote:
> 
> --  
> David A. Black  
> dblack@wobblini.net

---

<div class="post-metadata">

**Author:** ![David\_A\_Black3](https://avatars.discourse-cdn.com/v4/letter/d/6a8cbe/32.png) [@David\_A\_Black3](https://rubytalk.org/u/David_A_Black3)\
**Post date:** [9 April 2004 11:09 UTC](https://rubytalk.org/t/need-help-with-recursion/10945/8 "2004-04-09T11:09:59Z")

</div>

Hi --

> \> 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.
> 
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;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:

&nbsp;&nbsp;def find\_files\_broken(dir)  
&nbsp;&nbsp;&nbsp;&nbsp;Dir.new(dir).reject {|f| /\A\.\.?\z/.match(f)} .each do |f|  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if File.stat(f).file?  
&nbsp;&nbsp;puts "File: #{f}"  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;elsif File.stat(f).directory?  
&nbsp;&nbsp;puts "Directory: #{f}"  
&nbsp;&nbsp;find\_files(f)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end

&nbsp;&nbsp;find\_files\_broken(Dir.pwd)

Here's a modified example that works:

&nbsp;&nbsp;def find\_files(dir)  
&nbsp;&nbsp;&nbsp;&nbsp;Dir.chdir(dir) do  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Dir["\*"].each do |f|  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if File.stat(f).file?  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;puts "File: #{f}"  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;elsif File.stat(f).directory?  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;puts "Directory: #{f}"  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;find\_files(f)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end

&nbsp;&nbsp;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

> **···**
>
> On Fri, 9 Apr 2004, ibotty wrote:
> 
> --  
> David A. Black  
> dblack@wobblini.net

---

<div class="post-metadata">

**Author:** ![Mark\_J\_Reed1](https://avatars.discourse-cdn.com/v4/letter/m/8491ac/32.png) [@Mark\_J\_Reed1](https://rubytalk.org/u/Mark_J_Reed1)\
**Post date:** [9 April 2004 16:29 UTC](https://rubytalk.org/t/need-help-with-recursion/10945/9 "2004-04-09T16:29:17Z")

</div>

“David A. Black” [dblack@wobblini.net](mailto:dblack@wobblini.net) writes:

> Hi –

> $ ls u\_score/  
> u\_file  
> $ ruby -e ‘File.rename(“u\_score/u\_s”, “u\_score/u s”)’  
> -e:1:in `rename’: No such file or directory -  
> u\_score/u\_s or u\_score/u s (Errno::ENOENT)  
> from -e:1

That’s because the filename is “u\_file”, not “u\_s”.

> I have to admit I have no idea why that happens or even what the error  
> exactly means. (What’s with the “or”?)

The error means simply that some file or directory, which the system  
needed to access in order to perform the rename, doesn’t exist.

The “or” inside the error message is there because the error can refer to  
either a file or directory. The “or” between the pathnames is there  
because the error might occur while processing either argument to rename:  
the source or the destination.

Obviously, if the destination file doesn’t exist, that’s not an error, because  
it’s not supposed to exist until after the rename. But if the destination  
is a pathname instead of just a bare filename, then one or more of the  
subdirectories on the way to the destination might not exist, and that  
would trigger the same error. For instance, if you’d done this:

```
    $ ruby -e 'File.rename("u_score/u_file", "u score/u_file")'

```

that would fail with a very similar error because the directory “u score”  
doesn’t exist.

(You could, of course, rename the directory itself:

```
    $ ruby -e 'File.rename("u_score", "u score");

```

That would work fine.)

-Mark

> **···**
>
> > On Sat, 10 Apr 2004, Robert Klemme wrote:

---

<div class="post-metadata">

**Author:** ![David\_A\_Black3](https://avatars.discourse-cdn.com/v4/letter/d/6a8cbe/32.png) [@David\_A\_Black3](https://rubytalk.org/u/David_A_Black3)\
**Post date:** [9 April 2004 16:31 UTC](https://rubytalk.org/t/need-help-with-recursion/10945/10 "2004-04-09T16:31:44Z")

</div>

Hi –

> **···**
>
> On Sat, 10 Apr 2004, David A. Black wrote:
> 
> > But here’s some rename weirdness I’ve discovered while doing this:
> > 
> > $ ls u\_score/  
> > u\_file  
> > $ ruby -e ‘File.rename(“u\_score/u\_s”, “u\_score/u s”)’  
> > -e:1:in `rename’: No such file or directory -  
> > u\_score/u\_s or u\_score/u s (Errno::ENOENT)  
> > from -e:1
> > 
> > I have to admit I have no idea why that happens or even what the error  
> > exactly means. (What’s with the “or”?)
> 
> Never mind. I am an idiot. “u\_s” != “u\_file”. (Private note to the  
> person who pointed this out: merci 🙂
> 
> David
> 
> –  
> David A. Black  
> [dblack@wobblini.net](mailto:dblack@wobblini.net)

---

<div class="post-metadata">

**Author:** ![Robert](https://avatars.discourse-cdn.com/v4/letter/r/e95f7d/32.png) [@Robert](https://rubytalk.org/u/Robert)\
**Post date:** [9 April 2004 21:14 UTC](https://rubytalk.org/t/need-help-with-recursion/10945/11 "2004-04-09T21:14:16Z")

</div>

“David A. Black” [dblack@wobblini.net](mailto:dblack@wobblini.net) schrieb im Newsbeitrag  
news:Pine.LNX.4.44.0404090846010.18453-100000@wobblini…

> Hi –
> 
> > 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.
> 
> Yes, actually I used Find.find in my example 🙂

I know. I included the other variant for the purpose of showing a different  
approach. 🙂

> You’re right about  
> the overzealous gsub’ing. I’m not sure how directories were supposed  
> to be handled, but I thought I was ignoring them, which I accidentally  
> wasn’t.

Me, too. But that’s an easy change:

Dir[File.join( dir, “\*\*”, “\*” )].each do |name|  
if File.file? name  
d, base = File.split name  
changed = base.dup.gsub!(“\_”, " ") and  
File.rename( name, File.join( d, changed ) )  
end  
end

or

Dir[File.join( dir, “\*\*”, “\*” )].each do |name|  
next unless File.file? name

d, base = File.split name  
changed = base.dup.gsub!(“\_”, " ") and  
File.rename( name, File.join( d, changed ) )  
end

Note: even when directories are ignored for the rename, the gsub on the  
complete name still can do harm and should by replaced by something along  
the lines of my suggestion (File.split and File.join).

Regards

```
robert

```

> **···**
>
> > On Sat, 10 Apr 2004, Robert Klemme wrote:

---

<div class="post-metadata">

**Author:** ![David\_A\_Black3](https://avatars.discourse-cdn.com/v4/letter/d/6a8cbe/32.png) [@David\_A\_Black3](https://rubytalk.org/u/David_A_Black3)\
**Post date:** [9 April 2004 21:52 UTC](https://rubytalk.org/t/need-help-with-recursion/10945/12 "2004-04-09T21:52:30Z")

</div>

Hi --

> **···**
>
> On Sat, 10 Apr 2004, Robert Klemme wrote:
> 
> > Note: even when directories are ignored for the rename, the gsub on the  
> > complete name still can do harm and should by replaced by something along  
> > the lines of my suggestion (File.split and File.join).
> 
> Yes -- that's what I meant when I said I thought I'd ignored them but  
> accidentally hadn't (i.e., by using gsub on the complete name).
> 
> David
> 
> --  
> David A. Black  
> dblack@wobblini.net
