How can I get the path for the last created file in a directory using Ruby?
views:
26answers:
3
A:
you can use the dir class to list all files and check the ctime or atime of the file object (ctime is the time the file was changed the last time, atime is the time the file was accessed the last time)
Dir.foreach("testdir") {|f| puts File.ctime(x) }
Nikolaus Gradwohl
2010-07-02 13:49:00
How do I order the foreach? I only want the file path with the most recent ctime.
Junior Developer
2010-07-02 13:56:09
using sort_by{ |f| f.ctime(f)}
Nikolaus Gradwohl
2010-07-02 14:09:18
A:
Dir.entries("testdir).reject{|f| f== '.' || f=='..'}.sort_by{|f| File.ctime(f)}.last
Steve Weet
2010-07-02 14:02:55
+1
A:
I think this is fairly brief:
Dir.glob(File.join(path, '*.*')).max { |a,b| File.ctime(a) <=> File.ctime(b) }
Mike Woodhouse
2010-07-02 14:05:12
You may want to change the file pattern to '*' unless all your files always have extensions. Please also be aware that files beginning with . will not be considered
Steve Weet
2010-07-02 17:35:23