Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Get the second most recent file from a directory?

Tags:

ruby

getfiles

I have this piece of script to acquire the most recent file in a directory

dir=Dir.glob("./logs/*").max_by {|f| File.mtime(f)}

I would like to also acquire the second most recent file from the directory. What could I write to achieve this?

like image 572
Whelandrew Avatar asked Sep 16 '25 02:09

Whelandrew


1 Answers

You can do as below using Ruby 2.2.0, which added an optional argument to the methods Enumerable#max_by, Enumerable#min_by and Enumerable#min etc.

Dir.glob("./logs/*").max_by(2) {|f| File.mtime(f)}
# gives first 2 maximun.
# If you want the second most recent
Dir.glob("./logs/*").max_by(2) {|f| File.mtime(f)}.last

max_by(n) {|obj| block } → obj

If the n argument is given, minimum n elements are returned as an array.

like image 200
Arup Rakshit Avatar answered Sep 17 '25 17:09

Arup Rakshit