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


当前回答

def get_path_content(dir)
  queue = Queue.new
  result = []
  queue << dir
  until queue.empty?
    current = queue.pop
    Dir.entries(current).each { |file|
      full_name = File.join(current, file)
      if not (File.directory? full_name)
        result << full_name
      elsif file != '.' and file != '..'
          queue << full_name
      end
    }
  end
  result
end

返回文件在目录和所有子目录中的相对路径

其他回答

这是对我有效的方法:

Dir.entries(dir).select { |f| File.file?(File.join(dir, f)) }

Dir。Entries返回一个字符串数组。然后,我们必须提供文件的完整路径file .file?,除非dir等于我们当前的工作目录。这就是File.join()的原因。

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

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.glob('path/**/*').select { |e| File.file? e }

或者任何不是目录的东西(File.file?将拒绝非常规文件):

Dir.glob('path/**/*').reject { |e| File.directory? e }

可选择的解决方案

在Dir等基于模式的查找方法上使用Find# Find。Glob实际上更好。请参阅“用Ruby递归列出目录的一行程序?”

下面的代码片段精确地显示了目录内的文件名称,跳过子目录和“。”,“..”带点的文件夹:

Dir.entries("your/folder").select { |f| File.file? File.join("your/folder", f) }

你可能还想使用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