File renaming question

Hi,
I just want to do a simple case-changing operation, if needed. The file
renaming scheme below works for me, but, if any files in my directory
are already lowercase, then, the script fails. How can I accommodate
files that may or may not be lowercase to begin with and just make them
lowercase, whatever they originally were. It seems to me that the “!” is
what’s demanding that my original files here be upper-case, but, I can’t
seem to get the thing to work without that “!.”

Thanks,
Peter

require ‘FileUtils’

Dir.chdir(“C:/bitmaps/notif”)

Dir.glob("*.pdf").each do |file|
File.rename("#{file}", “#{file.downcase!}”)
FileUtils.mv(file, “c:/bitmaps/notif/scratch”)
end

Alle mercoledì 11 aprile 2007, Peter B. ha scritto:

Peter

You’re right, what is making your program fail is the !. The problem is
that
String#downcase! returns nil when the string is already downcase, so the
call
to rename becomes:

File.rename("#{file}", “”)

(nil.to_s returns an empty string), and obviously fails. So here, you
need to
use downcase, which always returns the string with all characters
downcased.
You don’t specify what doesn’t work when you use downcase instead of
downcase!, but looking at your code, I think that it fails on the call
to mv.
If I’m right, the reason is that downcase doesn’t alter its receiver (in
this
case, file), so, when you pass file to FileUtils.mv, it still contains
the
upcase string. But, at that point, the file with the upcase name doesn’t
exist anymore and the method fails. Using downcase!, instead, file is
modified (downcased), so the first parameter to mv is the downcase
string,
which corresponds to an existing file. To solve your problem, you can
substitute downcase! with downcase in the call to rename and file with
file.downcase in the call to mv.

I hope this helps

Stefano

Stefano C. wrote:

To solve your problem, you can

substitute downcase! with downcase in the call to rename and file with
file.downcase in the call to mv.

I hope this helps

Stefano

Brilliant. Yes, that did it. I got rid of the screamer, !, and I put in
file.downcase with my move command. Thank you very much!