获取目录中的文件夹列表
如何使用 ruby 获取某个目录中存在的文件夹列表?
Dir.entries()
看起来很接近,但我不知道如何仅限于文件夹。
How do I get a list of the folders that exist in a certain directory with ruby?
Dir.entries()
looks close but I don't know how to limit to folders only.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
我发现这更有用且易于使用:
它获取当前目录中的所有文件夹,排除
.
和..
。要递归文件夹,只需使用
**
代替*
。Dir.glob
行也可以作为块传递给Dir.chdir
:I've found this more useful and easy to use:
it gets all folders in the current directory, excluded
.
and..
.To recurse folders simply use
**
in place of*
.The
Dir.glob
line can also be passed toDir.chdir
as a block:Jordan 很接近,但是
Dir.entries
没有返回File.directory?
期望的完整路径。试试这个:Jordan is close, but
Dir.entries
doesn't return the full path thatFile.directory?
expects. Try this:在我看来,
Pathname
比普通字符串更适合文件名。这将为您提供该目录中所有目录的数组作为 Pathname 对象。
如果你想要字符串
如果
directory_name
是绝对的,那么这些字符串也是绝对的。In my opinion
Pathname
is much better suited for filenames than plain strings.This gives you an array of all directories in that directory as Pathname objects.
If you want to have strings
If
directory_name
was absolute, these strings are absolute too.递归查找某个目录下的所有文件夹:
非递归版本:
注意:
Dir.[]
的工作方式类似于Dir.glob
。Recursively find all folders under a certain directory:
Non-recursively version:
Note:
Dir.[]
works likeDir.glob
.有了这个,您可以在一个目录中获取目录、子目录、子子目录的完整路径数组。递归方式。
我使用该代码将这些文件加载到 config/application 文件中。
此外,我们不再需要处理无聊的
.
和..
了。接受的答案需要处理它们。With this one, you can get the array of a full path to your directories, subdirectories, subsubdirectories in a recursive way.
I used that code to eager load these files inside
config/application
file.In addition we don't need deal with the boring
.
and..
anymore. The accepted answer needed to deal with them.您可以使用
FileTest
模块中的File.directory?
来确定文件是否是目录。将此与Dir.entries
结合起来,形成一个不错的单行:编辑: 根据 ScottD 的更正进行更新。
You can use
File.directory?
from theFileTest
module to find out if a file is a directory. Combining this withDir.entries
makes for a nice one(ish)-liner:Edit: Updated per ScottD's correction.
对于通用解决方案,您可能想要使用
这将适用于像
~/*/
这样的路径(您的主目录中的所有文件夹)。For a generic solution you probably want to use
This will work with paths like
~/*/
(all folders within your home directory).我们可以结合 Borh 的答案 和 johannes 的回答得到了一个相当优雅的解决方案来获取文件夹中的目录名称。
We can combine Borh's answer and johannes' answer to get quite an elegant solution to getting the directory names in a folder.
仅文件夹(排除“.”和“..”):
Dir.glob(File.join(path, "*", File::SEPARATOR))
文件夹和文件:
Dir .glob(File.join(路径, "*"))
Only folders ('.' and '..' are excluded):
Dir.glob(File.join(path, "*", File::SEPARATOR))
Folders and files:
Dir.glob(File.join(path, "*"))
我想你可以测试每个文件,看看它是否是一个带有
FileTest.directory 的目录? (文件名)
。有关详细信息,请参阅 FileTest 文档。I think you can test each file to see if it is a directory with
FileTest.directory? (file_name)
. See the documentation for FileTest for more info.