Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Most Recent File In A Directory

DZone's Guide to

Most Recent File In A Directory

·
Free Resource
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 self.directory?
    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) }
    files.last
  end
end
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}