DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Most Recent File In A Directory

  • submit to reddit
        To find the most recent file in a directory, you can use this extension to Pathname (if you aren't already using Pathname objects instead of File objects, check it out).

class Pathname
  # If this is a directory, returns the most recently modified 
  # file in this directory. Otherwise, return itself. If _matching_
  # is specified, only return files where filename =~ _matching_.
  # Returns nil if no files (or no matching files) are found.
  def most_recent_file(matching=/./)
    return self unless
    files = self.entries.collect { |file| self+file }.sort { |file1,file2| file1.mtime <=> file2.mtime }
    files.reject! { |file| ((file.file? and file.to_s =~ matching) ? false : true) }