Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

ruby - Sort order in `Dir.entries`

Is there a fixed/default sort order in which Dir.entries returns results? I know by experience that the first two entries are "." and "..".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to the Ruby language docs, Dir.entries() does not guarantee any particular order of the listed files, so if you require some order it's best to do it explicitly yourself.

For example, if you need to sort by file modification time (oldest to newest), you could do the following:

Dir.entries('.').sort_by { |x| File.mtime(x) }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...