How to order files by last modified time in ruby?
Asked Answered
S

3

31

How to get files in last modified time order in ruby? I was able to smash my keyboard enough to achieve this:

file_info = Hash[*Dir.glob("*").collect {|file| [file, File.ctime(file)]}.flatten]
sorted_file_info = file_info.sort_by { |k,v| v}
sorted_files = sorted_file_info.collect { |file, created_at| file }

But I wonder if there is more sophisticated way to do this?

Steerage answered 19/1, 2011 at 19:51 Comment(0)
S
62

How about simply:

# If you want 'modified time', oldest first
files_sorted_by_time = Dir['*'].sort_by{ |f| File.mtime(f) }

# If you want 'directory change time' (creation time for Windows)
files_sorted_by_time = Dir['*'].sort_by{ |f| File.ctime(f) }
Subheading answered 19/1, 2011 at 19:56 Comment(2)
Loved this in combination with the last method. Dir['*.png'].sort_by{ |f| File.ctime(f) }.last(5)Austinaustina
For fun: sorted = Dir['*'].sort_by(&File.method(:ctime))Subheading
P
10

A real problem with this is that *nix based file systems don't keep creation times for files, only modification times.

Windows does track it, but you're limited to that OS with any attempt to ask the underlying file system for help.

Also, ctime doesn't mean "creation time", it is "change time", which is the change time of the directory info POINTING to the file.

If you want the file's modification time, it's mtime, which is the change time of the file. It's a subtle but important difference.

Precontract answered 19/1, 2011 at 20:5 Comment(2)
Thanks for notice. I changed the question a little so most of them now answer to the correct question :) (I think you were the only answering the correct question at the beginning)Steerage
@Joni, You still might have a basic problem in the code because ctime is not the same as mtime. And, if the answers are not answering the question, don't change the question, expand on it so it's more apparent what you want.Precontract
E
4

Dir.glob("*").sort {|a,b| File.ctime(a) <=> File.ctime(b) }

Edible answered 19/1, 2011 at 19:54 Comment(3)
The Schwartzian sort_by is shorter, DRYer, and possibly more efficient (assuming enough files and a non-trivial time to invoke the ctime method for each).Subheading
But the UFO operator is awesomer!Edible
Damn, I cannot refute that! +1 for awesomer spaceships (when I get more votes in 4 hours :)Subheading

© 2022 - 2024 — McMap. All rights reserved.