gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:15:51 25 4
gpt4 key购买 nike

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

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

  1. 遍历 Dir.entries
  2. 构建路径 (File.expand_path)每一项
  3. 检查 File.directory?

简单的用例,如获取此目录中的所有 .svg 文件 似乎需要大量的循环/循环/检查。我是不是用错了 Ruby,或者说 Ruby 的这个方面看起来很不像 Ruby?

最佳答案

根据您的需要,FileDir可能做得很好。

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

所有 .svg 文件

如果由于某种原因可能存在扩展名为 .svg 的文件夹,您可以过滤 Pathname.glob 返回的路径名:

svg_files = Pathname.glob("folder/", "*.svg").select(&:file?)

如果你想要一个特定的语法:

class Pathname
def files
children.select(&:file?)
end
end

aDir = Pathname.new('folder/')
p aDir.files.find_all{ |f| f.extname == '.svg' }

迭代目录树

Pathname#find会有帮助。

关于ruby - 为什么 Ruby 的文件相关类型是基于字符串的(字符串类型的)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41629767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com