29

What's an idiomatic way to find the most recently modified file within a directory?

user664833
  • 18,397
  • 19
  • 91
  • 140
Mike
  • 19,267
  • 11
  • 56
  • 72

3 Answers3

60
Dir.glob("*").max_by {|f| File.mtime(f)}
Steve Wilhelm
  • 6,200
  • 2
  • 32
  • 36
  • Beautiful solution. Thank you. – Mike Jan 28 '11 at 00:41
  • 6
    Dir.glob("/path/to/search/**/*.*").max_by {|f| File.mtime(f)} – WiredIn Sep 01 '15 at 18:22
  • @WiredIn 's comment reduces the results to files which have a period in them (only files with an extension). See following for including 'hidden' dotfiles... https://stackoverflow.com/questions/11385795/ruby-list-directory-with-dir-including-dotfiles-but-not-and – ives Jan 25 '19 at 01:09
4

I'm not sure if there really is an idiom for this. I would do

Dir["*"].sort_by { |file_name| File.stat(file_name).mtime }

Edit

Seeing how three people gave more or less the same answer at the same time. This must be it.

EnabrenTane
  • 7,428
  • 2
  • 26
  • 44
  • Downvoted because this didn't answer the OP's question (returns sorted list of times instead of the most recent one). It's also less concise than the other two answers. – ives Jan 25 '19 at 01:13
  • You can do better obviously. Why didn't you answer it then? – von spotz Jul 31 '23 at 08:28
3
Dir["*"].sort { |a,b| File.mtime(a) <=> File.mtime(b) }.last

This is not recursive.

cam
  • 14,192
  • 1
  • 44
  • 29