views:

44

answers:

2

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

+8  A: 
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

sepp2k
I'm actually looking for how to find the most recently modified folder rather than file, so File.new throws and error, and there is no Dir.mtime
Dasmowenator
@Sam: `File.new` does not appear anywhere in my code and `File.mtime` works just fine with a directory name as an argument. Don't try to "fix" my code, it works as-is.
sepp2k
This is really close to working but Dir.glob() returns directories AND files, and I only want directories. I found thatDir.glob("*").delete_if{|entry| entry.include? "."}.max_by{|f| File.mtime(f)}works for this, but it assumes that none of your directories have periods in them...
Dasmowenator
@Dasmowenator: `Dir.glob("*")` includes files and directories, `Dir.glob("*/")` only includes directories (notice the trailing `/`).
sepp2k
A: 

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)}
Dasmowenator