2016-04-06 24 views
1

看來由Pathname的.children方法返回的文件系統實體的順序是任意的,或者至少不是按字母順序排列的。在Ruby路徑名中排序.children

有沒有辦法讓這些按字母順序通過文件系統返回,而不是在返回的數組上調用.sort

回答

3

路徑名的children其實就是做:

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和迭代傳入的目錄中沒有規定告訴操作系統通過特定的順序進行排序。

What is the "directory order" of files in a directory (used by ls -U)?」可能是你感興趣的。

+0

儘管我很欣賞投票和所有內容,請閱讀http://stackoverflow.com/help/someone-answers中的最後一段。 –

+0

我發現一個奇怪的政策。我從來沒有在接受的答案和感謝那個答案之間的心理聯繫:) –

+0

當你理解SO的目標時,這並不奇怪。這不是一個討論論壇,通過評論來回發言是不鼓勵的,因爲它們是爲了澄清和建議。還有其他機制可用於此。 –