31

如何在ruby中以最后修改时间顺序获取文件?我能够粉碎我的键盘来实现这一点:

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 }

但我想知道是否有更复杂的方法来做到这一点?

4

3 回答 3

62

简单地说:

# 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) }
于 2011-01-19T19:56:04.483 回答
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.

于 2011-01-19T20:05:11.630 回答
4

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

于 2011-01-19T19:54:39.780 回答