rubysortingpathname

Ordering in Ruby Pathname .children


It seems the order of the filesystem entities returned by Pathname's .children method is arbitrary or at least not alphabetical.

Is there a way to have these returned in alphabetical order via the file system rather than calling .sort on the returned array?


Solution

  • Pathname's children is actually doing:

    def children(with_directory=true)
      with_directory = false if @path == '.'
      result = []
      Dir.foreach(@path) {|e|
        next if e == '.' || e == '..'
        if with_directory
          result << self.class.new(File.join(@path, e))
        else
          result << self.class.new(e)
        end
      }
      result
    end
    

    Dir.foreach calls the OS and iterates the directory passed in. There is no provision for telling the OS to sort by a particular order.

    "What is the "directory order" of files in a directory (used by ls -U)?" is probably of interest to you.