Renaming Files

G

Gabriel Dragffy

Hi, I'm just trying to rename a whole load of files in a directory.
Been palying with IRB. My code doesn't work, no doubt because I
fluffed it.

irb(main):041:0> Dir.entries('.').each do |f|
irb(main):042:1* next if f=="." or f==".."
irb(main):043:1> File.move( f, f.gsub!( /\s/, '_' ) )
irb(main):044:1> end
Errno::ENOENT: No such file or directory -
Animating_Reality_2pm_26th_July_2007.MP3
from /opt/local/lib/ruby/1.8/ftools.rb:106:in `stat'
from /opt/local/lib/ruby/1.8/ftools.rb:106:in `move'
from (irb):43
from (irb):41:in `each'
from (irb):41
from :0

What's the best way of doing this, please?

Regards

Gabriel
 
G

Gabriel Dragffy

The problem here is the ! on the gsub. This is changing the
contents of f *before* it gets passed to the function:

def show(a, b)
puts "[#{a}] [#{b}]"
end

x = "Here is a string"

show(x, x.gsub!(/\s/,'_'))

results in

[Here_is_a_string] [Here_is_a_string]

But change the gsub! to a plain gsub and you get

[Here is a string] [Here_is_a_string]

because a plain gsub returns a copy of the modified string without
modifying the original.

Only use the ! versions when you are absolutely sure you need to.

Thank you so much for these replies (Peter & Stefano). That makes
perfect sense. As soon as you pointed out gsub! was doing what is was
supposed to :)
Thanks. I just renamed a directory of about 30 files in 0.5 seconds
with that one.

Just another quicky, if I wanna rename all the files in the directory
is what I did OK, using:
next if f=="." or f==".."

I just feel there must a better way?

Best regards Gabriel
 
S

Stefano Crocco

Alle gioved=EC 23 agosto 2007, Gabriel Dragffy ha scritto:
Just another quicky, if I wanna rename all the files in the directory =A0
is what I did OK, using:
=A0=A0=A0=A0=A0=A0=A0=A0next if f=3D=3D"." or f=3D=3D".."

I just feel there must a better way?

If you want to rename only files, then you should do

next unless File.file? f

This way, you skip not only the given directory and its parent, but also an=
y=20
directory inside the current. If you're sure the given directory contains=20
only files, then you're approach and mine should be equivalent (although, i=
n=20
my opinion, mine makes clearer why you're skipping those entries).

Stefano
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top