From: Stefano Crocco Date: 2007-04-12T03:27:48+09:00 Subject: Re: File renaming question Alle mercoled狸 11 aprile 2007, Peter Bailey ha scritto: > 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 > ... 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