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?
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 }
d,f = Dir.glob('*').partition{|d|test(?d,d)}
d.sort.each{|x|puts x}
f.sort.each{|y|puts y}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With