Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort order in `Dir.entries`

Tags:

Is there a fixed/default sort order in which Dir.entries returns results? I know by experience that the first two entries are "." and "..".

like image 959
Prasanna K Rao Avatar asked Sep 12 '11 14:09

Prasanna K Rao


1 Answers

According to the Ruby language docs, Dir.entries() does not guarantee any particular order of the listed files, so if you require some order it's best to do it explicitly yourself.

For example, if you need to sort by file modification time (oldest to newest), you could do the following:

Dir.entries('.').sort_by { |x| File.mtime(x) } 
like image 100
maerics Avatar answered Sep 29 '22 02:09

maerics