Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, how do you list/sort files before folders in a directory listing?

I have to following code in ruby:

<%
  files = Dir.glob('/**/*')
  files.each do |file|
    puts file
  end
%>

It outputs (for example):

/dirA/file1.txt
/dirA/file2.txt
/dirB/file1.txt
/file1.txt
/file2.txt
/subdirA/file1.txt

I want it to output it like this:

/file1.txt
/file2.txt
/dirA/file1.txt
/dirA/file2.txt
/dirB/file1.txt
/subdirA/file1.txt

Basically, I'd like to have the files displayed before the directories. Is there a sorting command I can use?

like image 249
James Nine Avatar asked Oct 09 '10 00:10

James Nine


2 Answers

I believe this should work for you:

files = Dir.glob('**/*')
files = files.map { |file| [file.count("/"), file] }
files = files.sort.map { |file| file[1] }
files.each do |file|
  puts file
end

Change "/" to ?/ if you're on Ruby 1.8.

Or, as a one-liner: :)

Dir.glob('**/*').map { |file| [file.count("/"), file] }.sort.map { |file| file[1] }.each { |file| puts file }
like image 191
Amadan Avatar answered Oct 27 '22 15:10

Amadan


d,f = Dir.glob('*').partition{|d|test(?d,d)}
d.sort.each{|x|puts x}
f.sort.each{|y|puts y}
like image 26
ghostdog74 Avatar answered Oct 27 '22 16:10

ghostdog74