如何在 ruby 中按上次修改时间对文件进行排序?
如何在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简单来说怎么样:
How about simply:
一个真正的问题是基于 *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.Dir.glob("*").sort {|a,b| File.ctime(a) <=>;文件.ctime(b) }
Dir.glob("*").sort {|a,b| File.ctime(a) <=> File.ctime(b) }