为什么Ruby的文件相关类型基于字符串(字符串类型)?

Gis*_*shu 5 ruby strong-typing

例如,Dir.entries返回字符串数组与包含FileDir实例的数组。Dir和File类型的大多数方法。相比之下,这些实例是无生气的。

没有Dir#foldersDir#files-我明确地

  1. 循环 Dir.entries
  2. File.expand_path为每个项目建立路径()
  3. 校验 File.directory?

简单的用例(例如,获取此目录中的所有.svg 文件)似乎需要大量的操作/循环/检查。我使用Ruby时是否错了,还是Ruby的这个方面看起来很不正常?

Eri*_*nil 4

根据您的需要,File或者Dir可能会很好。

当您需要链接命令并且(理所当然地)认为仅使用带有字符串参数的类方法感觉不符合 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 文件

如果由于某种原因可能存在带有.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会有帮助的。