Sort order in `Dir.entries`

前端 未结 4 2034
逝去的感伤
逝去的感伤 2020-12-03 07:33

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

相关标签:
4条回答
  • 2020-12-03 08:07

    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.

    0 讨论(0)
  • 2020-12-03 08:10

    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) }
    
    0 讨论(0)
  • 2020-12-03 08:12

    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}"
    
    0 讨论(0)
  • 2020-12-03 08:15

    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

    0 讨论(0)
提交回复
热议问题