开发者

How to order files by last modified time in ruby?

开发者 https://www.devze.com 2023-02-05 19:54 出处:网络
How to get files in last modified time order in ruby? I was able to smash开发者_JAVA技巧 my keyboard enough to achieve this:

How to get files in last modified time order in ruby? I was able to smash开发者_JAVA技巧 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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消