如何在ruby中按上次修改时间订购文件?

时间:2021-10-04 15:05:57

How to get files in last modified time order in ruby? I was able to smash my keyboard enough to achieve this:

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

But I wonder if there is more sophisticated way to do this?

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

3 个解决方案

#1


54  

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

#2


9  

A real problem with this is that *nix based file systems don't keep creation times for files, only modification times.

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

Windows does track it, but you're limited to that OS with any attempt to ask the underlying file system for help.

Windows会跟踪它,但您只能尝试向底层文件系统寻求帮助。

Also, ctime doesn't mean "creation time", it is "change time", which is the change time of the directory info POINTING to the file.

此外,ctime并不意味着“创建时间”,而是“更改时间”,这是目录信息POINTING到文件的更改时间。

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.

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

#3


3  

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

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

#1


54  

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

#2


9  

A real problem with this is that *nix based file systems don't keep creation times for files, only modification times.

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

Windows does track it, but you're limited to that OS with any attempt to ask the underlying file system for help.

Windows会跟踪它,但您只能尝试向底层文件系统寻求帮助。

Also, ctime doesn't mean "creation time", it is "change time", which is the change time of the directory info POINTING to the file.

此外,ctime并不意味着“创建时间”,而是“更改时间”,这是目录信息POINTING到文件的更改时间。

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.

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

#3


3  

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

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