在Ruby中获取目录数组(不包括文件)的最快,最优化,单行方式是什么?
包含文件怎么样?
答案 0 :(得分:164)
Dir.glob("**/*/") # for directories
Dir.glob("**/*") # for all files
而不是Dir.glob(foo)
你也可以写Dir[foo]
(但是Dir.glob
也可以取一个块,在这种情况下它会产生每个路径而不是创建一个数组。)
答案 1 :(得分:53)
我相信这里没有任何解决方案可以处理隐藏目录(例如'.test'):
require 'find'
Find.find('.') { |e| puts e if File.directory?(e) }
答案 2 :(得分:27)
有关目录列表,请尝试
Dir['**/']
文件列表更难,因为在Unix目录中也是一个文件,因此您需要测试类型或从返回列表中删除条目,这是其他条目的父级。
Dir['**/*'].reject {|fn| File.directory?(fn) }
简单地列出所有文件和目录
Dir['**/*']
答案 3 :(得分:7)
只有目录
`find -type d`.split("\n")
目录和普通文件
`find -type d -or -type f`.split("\n")`
require "pathname"
def rec_path(path, file= false)
puts path
path.children.collect do |child|
if file and child.file?
child
elsif child.directory?
rec_path(child, file) + [child]
end
end.select { |x| x }.flatten(1)
end
# only directories
rec_path(Pathname.new(dir), false)
# directories and normal files
rec_path(Pathname.new(dir), true)
答案 4 :(得分:6)
如此处的其他答案所述,您可以使用Dir.glob
。请记住,文件夹中可能包含许多奇怪的字符,而glob参数是模式,因此某些字符具有特殊含义。因此,做以下事情是不安全的:
Dir.glob("#{folder}/**/*")
取而代之的是:
Dir.chdir(folder) { Dir.glob("**/*").map {|path| File.expand_path(path) } }
答案 5 :(得分:2)
在PHP或其他语言中获取目录及其所有子目录的内容,您必须编写一些代码行,但在Ruby中需要2行:
require 'find'
Find.find('./') do |f| p f end
这将打印当前目录及其所有子目录的内容。
或更短,您可以使用’**’
表示法:
p Dir['**/*.*']
您将用PHP或Java编写多少行来获得相同的结果?
答案 6 :(得分:0)
虽然不是单行解决方案,但我认为这是使用ruby调用的最佳方式。
首先以递归方式删除所有文件 第二个删除所有空目录
Dir.glob("./logs/**/*").each { |file| File.delete(file) if File.file? file }
Dir.glob("./logs/**/*/").each { |directory| Dir.delete(directory) }
答案 7 :(得分:0)
这是一个将Rails项目目录的动态发现与Dir.glob结合起来的示例:
dir = Dir.glob(Rails.root.join('app', 'assets', 'stylesheets', '*'))
答案 8 :(得分:-1)
Dir.open(Dir.pwd).map { |h| (File.file?(h) ? "#{h} - file" : "#{h} - folder") if h[0] != '.' }
点返回nil,使用compact