What's an idiomatic way to find the most recently modified file within a directory?
Asked
Active
Viewed 6,495 times
3 Answers
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
-
6Dir.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
-
3
Dir["*"].sort { |a,b| File.mtime(a) <=> File.mtime(b) }.last
This is not recursive.

cam
- 14,192
- 1
- 44
- 29