4

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?

Whelandrew
  • 195
  • 10

2 Answers2

8

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.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
2
dir = Dir.glob("./logs/*").sort_by { |f| File.mtime(f) }
puts dir[-2]

or

dir = Dir.glob("./logs/*").sort_by { |f| File.mtime(f) }.reverse
puts dir[1]

.sort_by will return array of files sorted by mtime from oldest to newest, so you can access most recent file with dir[-1](last array element), the second most recent with dir[-2] etc. Or you can revert array and use dir[0], dir[1] etc. correspondingly.

Rustam Gasanov
  • 15,290
  • 8
  • 59
  • 72