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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With