Ruby “glob”: How to process each file in a directory that matches a certain pattern

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:

  1. I create a list of all *.WMA files in the current directory.
  2. For each filename object (which is a String), I create a new File object named file.
  3. I call the mtime method of my file object to get a Time object that represents the modification time of the file.
  4. I create a new_filename object, which is a String that represents the new filename as I want it, where the format for a file created today would be 2008-10-28.wma.
  5. I call the rename method of the File class to rename the current file from filename to new_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.