我想使用Ruby从一个文件夹中获得所有文件名。
当前回答
您还有快捷方式选项
Dir["/path/to/search/*"]
如果你想在任何文件夹或子文件夹中找到所有Ruby文件:
Dir["/path/to/search/**/*.rb"]
其他回答
这对我来说很管用:
如果你不想要隐藏文件[1],使用Dir[]:
# With a relative path, Dir[] will return relative paths
# as `[ './myfile', ... ]`
#
Dir[ './*' ].select{ |f| File.file? f }
# Want just the filename?
# as: [ 'myfile', ... ]
#
Dir[ '../*' ].select{ |f| File.file? f }.map{ |f| File.basename f }
# Turn them into absolute paths?
# [ '/path/to/myfile', ... ]
#
Dir[ '../*' ].select{ |f| File.file? f }.map{ |f| File.absolute_path f }
# With an absolute path, Dir[] will return absolute paths:
# as: [ '/home/../home/test/myfile', ... ]
#
Dir[ '/home/../home/test/*' ].select{ |f| File.file? f }
# Need the paths to be canonical?
# as: [ '/home/test/myfile', ... ]
#
Dir[ '/home/../home/test/*' ].select{ |f| File.file? f }.map{ |f| File.expand_path f }
现在,Dir。条目将返回隐藏的文件,并且您不需要通配符asterix(您可以直接将目录名传递给变量),但它将直接返回basename,因此File. xml将返回文件。XXX函数不能工作。
# In the current working dir:
#
Dir.entries( '.' ).select{ |f| File.file? f }
# In another directory, relative or otherwise, you need to transform the path
# so it is either absolute, or relative to the current working dir to call File.xxx functions:
#
home = "/home/test"
Dir.entries( home ).select{ |f| File.file? File.join( home, f ) }
[1] .dotfile在unix上,我不知道Windows上
在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(dir).select { |f| File.file?(File.join(dir, f)) }
Dir。Entries返回一个字符串数组。然后,我们必须提供文件的完整路径file .file?,除非dir等于我们当前的工作目录。这就是File.join()的原因。
如果你用空格创建目录:
mkdir "a b"
touch "a b/c"
你不需要转义目录名,它会自动完成:
p Dir["a b/*"] # => ["a b/c"]
Dir.entries(folder)
例子:
Dir.entries(".")
来源:http://ruby-doc.org/core/classes/Dir.html method-c-entries
推荐文章
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?
- RVM不是一个函数,用' RVM use…’不会起作用
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- 最好的打印散列的方法
- 如何删除文件中的特定行?
- Rails:dependent =>:destroy VS:dependent =>:delete_all
- 我可以在不包含Ruby模块的情况下调用实例方法吗?
- 如何将新项目添加到哈希
- 测试一个Ruby类是否是另一个类的子类
- 什么时候使用Struct vs. OpenStruct?
- 数组到哈希Ruby
- 使用Java重命名文件