Why does Ruby seem to access files in a directory randomly?

前端 未结 2 1539
Happy的楠姐
Happy的楠姐 2021-01-12 16:50

Is this by design?

Here\'s the code:

class FileRenamer
    def RenameFiles(folder_path)    
        files = Dir.glob(folder_path + \"/*\")
    end
en         


        
2条回答
  •  孤独总比滥情好
    2021-01-12 17:40

    The order should be the same every time on a particular OS, however it is different across operating systems.

    The behaviour or Dir.glob can not be relied upon to be the same across different OSs. Not sure if this is by design, but rather an artefact of the filesystems.

    On Windows and Linux the results are sorted by hierarchy, and then alphabetically; On Mac OS X the results are sorted alphabetically.

    You could mitigate the effect by calling sort on your results e.g.:

    files = Dir.glob("./*").sort
    

    or if you wanted it case insensitive, perhaps:

     files = Dir.glob("./*").sort {|a,b| a.upcase <=> b.upcase}
    

提交回复
热议问题