In Ruby, how do you list / sort files in front of folders in a directory list?

I need to execute the 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 him to output it as follows:

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

Basically, I would like files to appear in front of directories. Is there a sort command that I can use?

+5
source share
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 are on Ruby 1.8.

Or, as a single line: :)

Dir.glob('**/*').map { |file| [file.count("/"), file] }.sort.map { |file| file[1] }.each { |file| puts file }
+6
source
d,f = Dir.glob('*').partition{|d|test(?d,d)}
d.sort.each{|x|puts x}
f.sort.each{|y|puts y}
+1
source

All Articles