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


当前回答

Dir.entries(folder)

例子:

Dir.entries(".")

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

其他回答

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

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

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

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

这是一个在目录中查找文件的解决方案:

files = Dir["/work/myfolder/**/*.txt"]

files.each do |file_name|
  if !File.directory? file_name
    puts file_name
    File.open(file_name) do |file|
      file.each_line do |line|
        if line =~ /banco1/
          puts "Found: #{line}"
        end
      end
    end
  end
end

要递归地获取所有文件(严格来说只针对文件):

Dir.glob('path/**/*').select { |e| File.file? e }

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

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

可选择的解决方案

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

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

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