How to order files by last modified time in ruby?

≯℡__Kan透↙ 提交于 2019-11-28 21:08:39
Phrogz

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) }

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!