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

Is it for design?

Here is 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." 

Files seem to be randomly selected, not the way they appear in Nautilus.

enter image description here

Is it for design? I'm just curious.

+6
ruby dir
source share
1 answer

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

Behavior or Dir.glob can not rely on the same thing in different operating systems. Not sure if this is by design, but rather an artifact of file systems.

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

You can reduce the effect by calling sorting according to your results, for example:

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

or if you want the case insensitive, perhaps:

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

All Articles