Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Finding most recently modified file

Tags:

idioms

ruby

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

like image 468
Mike Avatar asked Jan 28 '11 00:01

Mike


3 Answers

Dir.glob("*").max_by {|f| File.mtime(f)}
like image 102
Steve Wilhelm Avatar answered Oct 20 '22 02:10

Steve Wilhelm


Dir["*"].sort { |a,b| File.mtime(a) <=> File.mtime(b) }.last

This is not recursive.

like image 3
cam Avatar answered Oct 20 '22 01:10

cam


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.

like image 3
EnabrenTane Avatar answered Oct 20 '22 01:10

EnabrenTane