我想使用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

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

其他回答

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

您还有快捷方式选项

Dir["/path/to/search/*"]

如果你想在任何文件夹或子文件夹中找到所有Ruby文件:

Dir["/path/to/search/**/*.rb"]

就我个人而言,我发现这对于在文件夹中循环文件最有用,前瞻性安全:

Dir['/etc/path/*'].each do |file_name|
  next if File.directory? file_name 
end

在IRB上下文中,您可以使用以下命令获取当前目录中的文件:

file_names = `ls`.split("\n")

你也可以在其他目录上这样做:

file_names = `ls ~/Documents`.split("\n")

这是对我有效的方法:

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

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