Techioz Blog

Ruby での順序付け パス名 .children

概要

Pathname の .children メソッドによって返されるファイルシステム エンティティの順序は任意であるか、少なくともアルファベット順ではないようです。

返された配列に対して .sort を呼び出すのではなく、ファイル システムを介してこれらをアルファベット順で返す方法はありますか?

解決策

Pathname の子は実際に次のことを行っています。

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 は OS を呼び出し、渡されたディレクトリを繰り返し処理します。OS に特定の順序で並べ替えるよう指示する機能はありません。

「ディレクトリ内のファイルの「ディレクトリ順序」(ls -U で使用) は何ですか?おそらくあなたにとって興味があるでしょう。