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

前端 未结 3 330
逝去的感伤
逝去的感伤 2021-01-18 20:38

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

相关标签:
3条回答
  • 2021-01-18 21:29

    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("**/*") 
    
    0 讨论(0)
  • 2021-01-18 21:35
    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

    0 讨论(0)
  • 2021-01-18 21:41

    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)}
    
    0 讨论(0)
提交回复
热议问题