如何在 ruby​​ 中按上次修改时间对文件进行排序?

发布于 2024-10-12 16:54:26 字数 304 浏览 5 评论 0原文

如何在 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 }

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

維他命╮ 2024-10-19 16:54:26

简单来说怎么样:

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

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) }
坚持沉默 2024-10-19 16:54:26

一个真正的问题是基于 *nix 的文件系统不保留文件的创建时间,只保留修改时间。

Windows 确实会跟踪它,但您只能在该操作系统上尝试向底层文件系统寻求帮助。

另外, ctime 不会意思是“创建时间”,它是“更改时间”,即指向文件的目录信息的更改时间。

如果您想要文件的修改时间,则为 mtime ,这是文件的更改时间。这是一个微妙但重要的区别。

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.

眼眸里的那抹悲凉 2024-10-19 16:54:26

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文