用一行代码递归列出Ruby中的目录?

时间:2022-09-28 22:32:22

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

在Ruby中获得目录数组(不包括文件)的最快、最优化的单行方法是什么?

How about including files?

包括文件怎么样?

9 个解决方案

#1


150  

Dir.glob("**/*/") # for directories
Dir.glob("**/*") # for all files

Instead of Dir.glob(foo) you can also write Dir[foo] (however Dir.glob can also take a block, in which case it will yield each path instead of creating an array).

您还可以编写Dir[foo](然而是Dir)。glob还可以使用一个块,在这种情况下,它将生成每个路径,而不是创建一个数组)。

Ruby Glob Docs

Ruby水珠文档

#2


51  

I believe none of the solutions here deal with hidden directories (e.g. '.test'):

我认为这里没有一个解决方案涉及隐藏目录(例如。“test”):

require 'find'
Find.find('.') { |e| puts e if File.directory?(e) }

#3


26  

For list of directories try

对于目录列表,请尝试

Dir['**/']

List of files is harder, because in Unix directory is also a file, so you need to test for type or remove entries from returned list which is parent of other entries.

文件列表比较困难,因为在Unix目录中也是一个文件,所以您需要测试类型或删除返回列表中的条目,该列表是其他条目的父类。

Dir['**/*'].reject {|fn| File.directory?(fn) }

And for list of all files and directories simply

以及所有文件和目录的列表

Dir['**/*']

#4


5  

Fast one liner

Only directories

只有目录

`find -type d`.split("\n")

Directories and normal files

目录和正常的文件

`find -type d -or -type f`.split("\n")`

Pure beautiful ruby

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)

#5


5  

As noted in other answers here, you can use Dir.glob. Keep in mind that folders can have lots of strange characters in them, and glob arguments are patterns, so some characters have special meanings. As such, it's unsafe to do something like the following:

正如这里其他答案中提到的,您可以使用Dir.glob。请记住,文件夹中可能有很多奇怪的字符,而glob参数是模式,因此有些字符具有特殊的含义。因此,做以下事情是不安全的:

Dir.glob("#{folder}/**/*")

Instead do:

而不是做的事:

Dir.chdir(folder) { Dir.glob("**/*").map {|path| File.expand_path(path) } }

#6


2  

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:

在PHP或其他语言中,要获取目录及其所有子目录的内容,必须编写一些代码行,但在Ruby中,需要2行:

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?

用PHP或Java写多少行才能得到相同的结果?

#7


1  

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

虽然不是一种单行解决方案,但我认为这是使用ruby调用来完成它的最佳方式。

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) }

#8


0  

Here's an example that combines dynamic discovery of a Rails project directory with Dir.glob:

下面这个例子结合了动态发现Rails项目目录和目录。

dir = Dir.glob(Rails.root.join('app', 'assets', 'stylesheets', '*'))

#9


-1  

Dir.open(Dir.pwd).map { |h| (File.file?(h) ? "#{h} - file" : "#{h} - folder") if h[0] != '.' }

dots return nil, use compact

点返回nil,使用紧凑型

#1


150  

Dir.glob("**/*/") # for directories
Dir.glob("**/*") # for all files

Instead of Dir.glob(foo) you can also write Dir[foo] (however Dir.glob can also take a block, in which case it will yield each path instead of creating an array).

您还可以编写Dir[foo](然而是Dir)。glob还可以使用一个块,在这种情况下,它将生成每个路径,而不是创建一个数组)。

Ruby Glob Docs

Ruby水珠文档

#2


51  

I believe none of the solutions here deal with hidden directories (e.g. '.test'):

我认为这里没有一个解决方案涉及隐藏目录(例如。“test”):

require 'find'
Find.find('.') { |e| puts e if File.directory?(e) }

#3


26  

For list of directories try

对于目录列表,请尝试

Dir['**/']

List of files is harder, because in Unix directory is also a file, so you need to test for type or remove entries from returned list which is parent of other entries.

文件列表比较困难,因为在Unix目录中也是一个文件,所以您需要测试类型或删除返回列表中的条目,该列表是其他条目的父类。

Dir['**/*'].reject {|fn| File.directory?(fn) }

And for list of all files and directories simply

以及所有文件和目录的列表

Dir['**/*']

#4


5  

Fast one liner

Only directories

只有目录

`find -type d`.split("\n")

Directories and normal files

目录和正常的文件

`find -type d -or -type f`.split("\n")`

Pure beautiful ruby

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)

#5


5  

As noted in other answers here, you can use Dir.glob. Keep in mind that folders can have lots of strange characters in them, and glob arguments are patterns, so some characters have special meanings. As such, it's unsafe to do something like the following:

正如这里其他答案中提到的,您可以使用Dir.glob。请记住,文件夹中可能有很多奇怪的字符,而glob参数是模式,因此有些字符具有特殊的含义。因此,做以下事情是不安全的:

Dir.glob("#{folder}/**/*")

Instead do:

而不是做的事:

Dir.chdir(folder) { Dir.glob("**/*").map {|path| File.expand_path(path) } }

#6


2  

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:

在PHP或其他语言中,要获取目录及其所有子目录的内容,必须编写一些代码行,但在Ruby中,需要2行:

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?

用PHP或Java写多少行才能得到相同的结果?

#7


1  

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

虽然不是一种单行解决方案,但我认为这是使用ruby调用来完成它的最佳方式。

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) }

#8


0  

Here's an example that combines dynamic discovery of a Rails project directory with Dir.glob:

下面这个例子结合了动态发现Rails项目目录和目录。

dir = Dir.glob(Rails.root.join('app', 'assets', 'stylesheets', '*'))

#9


-1  

Dir.open(Dir.pwd).map { |h| (File.file?(h) ? "#{h} - file" : "#{h} - folder") if h[0] != '.' }

dots return nil, use compact

点返回nil,使用紧凑型