One-liner to recursively list directories in Ruby?

2019-01-10 01:33发布

What is the fastest, most optimized, one-liner way to get an array of the directories (excluding files) in Ruby?

How about including files?

9条回答
干净又极端
2楼-- · 2019-01-10 02:14

Although not a one line solution, I think this is the best way to do it using ruby calls.

First delete all the files recursively
Second delete all the empty directories

Dir.glob("./logs/**/*").each { |file| File.delete(file) if File.file? file }
Dir.glob("./logs/**/*/").each { |directory| Dir.delete(directory) }
查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-10 02:16

In PHP or other languages to get the content of a directory and all its subdirectories, you have to write some lines of code, but in Ruby it takes 2 lines:

require 'find'
Find.find('./') do |f| p f end

this will print the content of the current directory and all its subdirectories.

Or shorter, You can use the ’**’ notation :

p Dir['**/*.*']

How many lines will you write in PHP or in Java to get the same result?

查看更多
趁早两清
4楼-- · 2019-01-10 02:28
Dir.open(Dir.pwd).map { |h| (File.file?(h) ? "#{h} - file" : "#{h} - folder") if h[0] != '.' }

dots return nil, use compact

查看更多
登录 后发表回答