Here's some sample Ruby source code that shows how to do something with every file in a directory, where you only work on filenames that match a pattern you're interested in. For example, in my case I'm only interested in processing files that end with the filename extension WMA
, so this first snippet of Ruby code shows how to print out the name of each file in a directory with the WMA
extension:
Dir.glob("*.WMA") {|file| # do something with the file here puts file }
I'm using WMA
in all caps there because these files were generated on a Windows computer, but my script is running on a Mac OS X system.
My real Ruby script
Now, what I'm doing with my real Ruby script is finding all these WMA
files, and converting their filenames, so a file's new name will be based on the modification time of that file. Let me first give you my Ruby code, then I'll describe how it works:
Dir.glob("*.WMA") {|filename| file = File.new(filename) mtime = file.mtime new_filename = "#{mtime.year}-#{mtime.month}-#{mtime.day}.wma" puts "Renaming #{filename} to #{new_filename} ..." File.rename(filename, new_filename) }
This script works like this:
- I create a list of all
*.WMA
files in the current directory. - For each
filename
object (which is aString
), I create a new File object namedfile
. - I call the
mtime
method of myfile
object to get a Time object that represents the modification time of the file. - I create a
new_filename
object, which is aString
that represents the new filename as I want it, where the format for a file created today would be2008-10-28.wma
. - I call the
rename
method of theFile
class to rename the current file fromfilename
tonew_filename
.
Now that you've seen this basic approach for how to do "something" to each file in a directory that matches a certain file naming pattern, you can of course do anything you want inside that processing block. For me, the hardest part when I wrote this script last night was digging into classes like Dir
, String
, and File
to find all the methods I needed.