gpt4 book ai didi

ruby - 有哪些方法可以在不脱壳的情况下检查文件是否存在于 ruby​​ 中?

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

有哪些使用 Ruby 的核心类/模块来检查文件是否存在而无需脱壳的方法?

也会理解为什么选择一种方法而不是另一种方法有意义的原因。例如:使用 Dir['**/*'].grep(/foo/) 是我发现使用正则表达式匹配路径的最短方法。

但是,我认为Pathname.new('.').find.any? { |pn| pn.fnmatch? "*foo*" 是一个不错的选择,因为 Pathname是一种跨平台解决方案,通常似乎“正常工作”。

是否有我遗漏的任何解决方案/类/模块?另外,希望得到涉及速度/效率分析的答案。

require 'minitest/autorun'
require 'pathname'

class TestTouch < Minitest::Test
include FileUtils
attr_reader :foo
def setup
@foo = Pathname.new('foo')
foo.delete if foo.exist?
end

def teardown
foo.delete if foo.exist?
end

def test_touch
touch foo
cwd = Pathname.new('.')
assert cwd.find.to_a.map(&:to_s).grep(/foo/).any?
assert cwd.find.any? { |pn| pn.fnmatch? "*foo*" }
assert cwd.join('foo').exist?
assert Dir['**/*'].grep(/foo/)
assert Dir.glob('**/*').grep(/foo/)
assert !Dir.glob('foo').empty?
assert File.exist?('foo')
end
end

最佳答案

试试这个

File.exist?(fname)
File.file?(fname)

但有时,如果您需要检查是否存在并以原子操作打开文件,最好只打开文件并通过挽救异常来处理丢失文件的情况。

为什么这是个好主意?当您处理数据库和缓存层时,这主要适用于后端的基础设施代码。有时,如果文件在获取分支和使用内容之间被删除或替换,那么您的代码不受影响可能很重要——当文件被删除时,句柄保持打开状态并且仍然可以使用!

begin
File.open(fname) { ... }
rescue Errno::ENOENT => e
...
end

ENOENT 是“找不到文件”的 C 库错误代码,有关所有错误代码的完整列表,请参阅 here .大多数 Ruby 的文件处理基本上只是底层 C 库的薄包装。正如您在浏览 File 类时可能已经注意到的那样。

关于ruby - 有哪些方法可以在不脱壳的情况下检查文件是否存在于 ruby​​ 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41607211/

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