Is there a fixed/default sort order in which Dir.entries
returns results? I know by experience that the first two entries are \".\"
and \"..\
I think there is no default sort order, but you can use Dir.entries('some_path_to_dir').sort
to sort them in ASC way.
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) }
Expanding on @maerics' answer ,the below ignores . && ..
, regex based filter , and select the latest file if desired.
Dir.chdir(in_dir)
target_file = Dir.entries(in_dir).select(|x|
x != '.' &&
x != '..' &&
x =~ /\somefile.txt\z/).sort_by{|f|File.mtime(f)}.last(1)
puts "here i am #{target_file}"
For others who may come here with the same doubt. A way to select only the files that match a regular expression and still be able to sort them the way you want is:
files_sorted_by_date = Dir["your regex"].sort_by { |x| File.birthtime(x) }.reverse
or
files_sorted_by_date = Dir["your regex"].sort_by { |x| File.birthtime(x) }
Depending on how you want your files sortes.
I couldn't do the same using the Dir.entries method