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

杀马特。学长 韩版系。学妹 提交于 2019-12-30 08:59:10

问题


Is this by design?

Here's the code:

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

puts "Renaming files..."

renamer = FileRenamer.new()
files = renamer.RenameFiles("/home/papuccino1/Desktop/Test")
puts files

puts "Renaming complete."

It seems to be fetching the files is random order, not as they are displayed in Nautilus.

Is this by design? I'm just curious.


回答1:


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}


来源:https://stackoverflow.com/questions/5529895/why-does-ruby-seem-to-access-files-in-a-directory-randomly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!