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


当前回答

您还有快捷方式选项

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

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

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

其他回答

在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

如果你用空格创建目录:

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

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

p Dir["a b/*"] # => ["a b/c"]
Dir.new('/home/user/foldername').each { |file| puts file }

您还有快捷方式选项

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

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

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