How to find the most resent files in a directory with ruby

I had to find some files for processing and wanted to find the latest file by modification date. So here is what I came up with:

Dir.entries(".").sort_by { |f| File.file?(f) ? File.mtime(f) : Time.mktime(0) }.reverse[0..9]

Explanation:

Dir.entries(".")

grab the entries in the current directory

.sort_by

pass the entries into the block for sorting

File.file?(?) ?

the condition entry for finding out if the entry is a file

F.mtime(f) :

if the condition returns true, sort by modification time

Time.mktime(0)

if the condition is false, use the mktime(0)

.reverse[0..1]

reverse the list and show 0 to 1 entries

Posted