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

前端 未结 3 329
逝去的感伤
逝去的感伤 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("**/*") 
    

提交回复
热议问题