How can you find the most recently modified folder (NOT A FILE) in a directory using Ruby?
views:
44answers:
2
+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
2010-07-08 19:39:04
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
2010-07-08 19:54:59
@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
2010-07-08 19:59:37
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
2010-08-19 14:01:12
@Dasmowenator: `Dir.glob("*")` includes files and directories, `Dir.glob("*/")` only includes directories (notice the trailing `/`).
sepp2k
2010-08-19 14:17:48
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
2010-07-08 19:58:06