gpt4 book ai didi

ruby - 如何在ruby中获取文件模式?

转载 作者:太空宇宙 更新时间:2023-11-03 17:29:06 26 4
gpt4 key购买 nike

我是 ruby​​ 文件 IO 的新手。我有一个带有 File 参数的函数,我需要确保该文件处于只读模式。

def myfunction(file)
raise ArgumentError.new() unless file.kind_of?(File)

#Assert that file is in read-only mode
end

如有任何帮助,我们将不胜感激!

最佳答案

如果你不需要报错,你可以使用reopen,我想是这样的:

file = file.reopen(file.path, "r")

我找不到其他方法来验证不存在写入流,但这里有一些可行的技巧。虽然我不喜欢在预期路径中使用异常抛出,但您可以使用 close_write:

begin
file.close_write
# you could actually raise an exception here if you want
# since getting here means the file was originally opened for writing
rescue IOError
# This error will be raised if the file was not opened for
# writing, so this is actually the path we want
end

关于ruby - 如何在ruby中获取文件模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52797474/

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