开发者

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

开发者 https://www.devze.com 2023-02-22 05:47 出处:网络
Is this by design? Here\'s the code: class FileRenamer def RenameFiles(folder_path) 开发者_如何学编程 files = Dir.glob(folder_path + \"/*\")

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.

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

Is this by design? I'm just curious.


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}


The answer from Scott is out of date. I ran Dir.glob on Mac OS 10.15.6 Catalina, and the files were not returned in alphabetical order. According to the ruby docs, the ordering is determined by the OS.

https://ruby-doc.org/core-2.5.1/Dir.html

Note that the pattern is not a regexp, it's closer to a shell glob. See File.fnmatch for the meaning of the flags parameter. Case sensitivity depends on your system (File::FNM_CASEFOLD is ignored), as does the order in which the results are returned.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号