How can you find the most recently modified folder (NOT A FILE) in a directory using Ruby?
Expanding off of sepp2k's answer a bit to add recursively checking all subdirectories for those coming across this:
#!/usr/bin/env ruby
if ARGV.count != 1 then raise RuntimeError, "Usage: newest.rb '/path/to/your dir'" end
Dir.chdir(ARGV[0])
newest_file = Dir.glob("**/").max_by {|f| File.mtime(f)}
if newest_file != nil then
puts newest_file.to_s + " " + File.mtime(newest_file).to_s
else
puts "No subdirectories"
end
and use this instead if you want all files and not just directories:
Dir.glob("**/*")
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
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)}