tags:

views:

26

answers:

3

How can I get the path for the last created file in a directory using Ruby?

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
How do I order the foreach? I only want the file path with the most recent ctime.
Junior Developer
using sort_by{ |f| f.ctime(f)}
Nikolaus Gradwohl
A: 
Dir.entries("testdir).reject{|f| f== '.' || f=='..'}.sort_by{|f| File.ctime(f)}.last
Steve Weet
+1  A: 

I think this is fairly brief:

Dir.glob(File.join(path, '*.*')).max { |a,b| File.ctime(a) <=> File.ctime(b) }
Mike Woodhouse
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