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


当前回答

如果你用空格创建目录:

mkdir "a b"
touch "a b/c"

你不需要转义目录名,它会自动完成:

p Dir["a b/*"] # => ["a b/c"]

其他回答

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(folder)

例子:

Dir.entries(".")

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

在获取目录中的所有文件名时,此代码段可用于拒绝两个目录[。, . .]和以a开头的隐藏文件。

files = Dir.entries("your/folder").reject {|f| File.directory?(f) || f[0].include?('.')}

如果你用空格创建目录:

mkdir "a b"
touch "a b/c"

你不需要转义目录名,它会自动完成:

p Dir["a b/*"] # => ["a b/c"]

您还有快捷方式选项

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

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

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