我想使用Ruby从一个文件夹中获得所有文件名。


当前回答

如果您想获得包含符号链接的文件名数组,请使用

Dir.new('/path/to/dir').entries.reject { |f| File.directory? f }

甚至

Dir.new('/path/to/dir').reject { |f| File.directory? f }

如果你不想使用符号链接,请使用

Dir.new('/path/to/dir').select { |f| File.file? f }

如其他答案所示,如果你想递归地获得所有文件,使用dir .glob('/path/to/dir/**/*')而不是dir .new('/path/to/dir')。

其他回答

Dir.new('/home/user/foldername').each { |file| puts file }

当加载操作目录中的所有文件名时,您可以使用

Dir.glob (*)

这将返回应用程序正在运行的上下文中的所有文件(注意,对于Rails,这是应用程序的顶级目录)

您可以在这里(https://ruby-doc.org/core-2.7.1/Dir.html#method-c-glob)进行额外的匹配和递归搜索

在Ruby 2.5中,你现在可以使用Dir.children。它以数组的形式获取文件名,除了"."和".."

例子:

Dir.children("testdir")   #=> ["config.h", "main.rb"]

http://ruby-doc.org/core-2.5.0/Dir.html#method-c-children

Dir.entries(folder)

例子:

Dir.entries(".")

来源:http://ruby-doc.org/core/classes/Dir.html method-c-entries

你可能还想使用Rake::FileList(如果你有Rake依赖):

FileList.new('lib/*') do |file|
  p file
end

根据API:

filelist是懒惰的。当给出可能的glob模式列表时 要包含在文件列表中的文件,而不是搜索文件 结构来查找文件,FileList保存后者的模式 使用。

https://docs.ruby-lang.org/en/2.1.0/Rake/FileList.html