Gis*_*shu 5 ruby strong-typing
例如,Dir.entries返回字符串数组与包含File或Dir实例的数组。Dir和File类型的大多数方法。相比之下,这些实例是无生气的。
没有Dir#folders或Dir#files-我明确地
Dir.entries File.expand_path为每个项目建立路径()File.directory?简单的用例(例如,获取此目录中的所有.svg 文件)似乎需要大量的操作/循环/检查。我使用Ruby时是否错了,还是Ruby的这个方面看起来很不正常?
当您需要链接命令并且(理所当然地)认为仅使用带有字符串参数的类方法感觉不符合 ruby 风格时,您可以使用Pathname. 它是一个标准库。
require 'pathname'
my_folder = Pathname.new('./')
dirs, files = my_folder.children.partition(&:directory?)
# dirs is now an Array of Pathnames pointing to subdirectories of my_folder
# files is now an Array of Pathnames pointing to files inside my_folder
Run Code Online (Sandbox Code Playgroud)
如果由于某种原因可能存在带有.svg扩展名的文件夹,您可以仅过滤返回的路径名Pathname.glob:
svg_files = Pathname.glob("folder/", "*.svg").select(&:file?)
Run Code Online (Sandbox Code Playgroud)
如果你想要特定的语法:
class Pathname
def files
children.select(&:file?)
end
end
aDir = Pathname.new('folder/')
p aDir.files.find_all{ |f| f.extname == '.svg' }
Run Code Online (Sandbox Code Playgroud)
Pathname#find会有帮助的。
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |