2

I'm iterating over the files in a given directory in ruby, ie:

Dir.each

I'd like to iterate over the files in sorted order - descending or ascending by last edit date. What's the shortest way to write code to do this, in ruby?

xpt
  • 20,363
  • 37
  • 127
  • 216
blueberryfields
  • 45,910
  • 28
  • 89
  • 168

1 Answers1

4

This will sort them in ascending order:

Dir['*'].sort_by{|f| File.mtime(f) }

if you want them in descending order, add reverse! which seems to be the fastest method:

Dir['*'].sort_by{|f| File.mtime(f) }.reverse!
Community
  • 1
  • 1
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
  • Or use `-File.mtime(f)`, which lets `sort_by` do the desired thing, rather than have it do an ascending sort and you `reverse` it afterwards to get the same result. – the Tin Man May 15 '13 at 18:54
  • 1
    @theTinMan didn't you state in your own benchmark in "http://stackoverflow.com/questions/2642182/sorting-an-array-in-descending-order-in-ruby" that `reverse!` is faster? ;-) – Patrick Oscity May 15 '13 at 20:20