Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you find the most recently modified folder in a directory using Ruby?

How can you find the most recently modified folder (NOT A FILE) in a directory using Ruby?

like image 318
Dasmowenator Avatar asked Jul 08 '10 19:07

Dasmowenator


2 Answers

Dir.glob("a_directory/*/").max_by {|f| File.mtime(f)}

Dir.glob("a_directory/*/") returns all the directory names in a_directory (as strings) and max_by returns the name of the directory for which File.mtime returns the greatest (i.e. most recent) date.

Edit: updated answer to match the updated question

like image 94
sepp2k Avatar answered Sep 28 '22 12:09

sepp2k


Find the most recently modified directory in the current directory:

folders = Dir["*"].delete_if{|entry| entry.include? "."}
newest = folders[0]
folders.each{|folder| newest = folder if File.mtime(folder) > File.mtime(newest)}
like image 28
Dasmowenator Avatar answered Sep 28 '22 14:09

Dasmowenator