# Get oldest File from Directory?

**URL:** <https://www.ruby-forum.com/t/get-oldest-file-from-directory/134386>\
**Category:** Ruby\
**Created:** [April 10, 2008, 1:10pm UTC](https://www.ruby-forum.com/t/get-oldest-file-from-directory/134386 "2008-04-10T13:10:37Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![sealedsun](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/e68b1a/32.png) [@sealedsun](https://www.ruby-forum.com/u/sealedsun)\
**Post date:** [April 10, 2008, 1:10pm UTC](https://www.ruby-forum.com/t/get-oldest-file-from-directory/134386/1 "2008-04-10T13:10:37Z")

</div>

Hey!

What is the easiest way to retrieve the oldest (oldest modification  
date) file from a directory?

thx ck

---

<div class="post-metadata">

**Author:** ![sealedsun](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/e68b1a/32.png) [@sealedsun](https://www.ruby-forum.com/u/sealedsun)\
**Post date:** [April 10, 2008, 1:28pm UTC](https://www.ruby-forum.com/t/get-oldest-file-from-directory/134386/2 "2008-04-10T13:28:41Z")

</div>

2008/4/10, Christian K. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> Hey!
> 
> What is the easiest way to retrieve the oldest (oldest modification  
> date) file from a directory?

def oldest\_file(dir)  
Dir.entries(dir).map { |e|  
File.join(dir, e)  
}.select { |f|  
File.file? f  
}.sort\_by { |f|  
File.mtime f  
}.first  
end

This ignores directories.

---

<div class="post-metadata">

**Author:** ![sealedsun](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/e68b1a/32.png) [@sealedsun](https://www.ruby-forum.com/u/sealedsun)\
**Post date:** [April 10, 2008, 1:32pm UTC](https://www.ruby-forum.com/t/get-oldest-file-from-directory/134386/3 "2008-04-10T13:32:06Z")

</div>

Stefan L. wrote:

> def oldest\_file(dir)  
> Dir.entries(dir).map { |e|  
> File.join(dir, e)  
> }.select { |f|  
> File.file? f  
> }.sort\_by { |f|  
> File.mtime f  
> }.first  
> end

Perfect, Thx!
