Ruby 自动删除临时文件?

编程入门 行业动态 更新时间:2024-10-14 00:26:11
本文介绍了Ruby 自动删除临时文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我很困惑.这是我的代码:

I'm confused. Here's my code:

require 'csv' require 'tempfile' f = Tempfile.new('csv','/tmp') f.write 'just wanna test' f.close p f.path

如果我打开输出路径,它是空的.

If I open the output path, it is empty.

我认为这是因为每次 ruby​​ 会话退出时,TempFile 都会自动从文件系统中删除.但是,我如何确切知道文件何时被删除?因为我想用它在我的 rails 应用程序中创建临时文件,所以我担心如果文件在使用之前被删除了.

I think this is because that the TempFile got automatically removed from the file system each time the ruby session exits. However, how do I know exactly when the file got deleted? Because I'm thinking to use it to create temp file within my rails app, I'm afraid if the file got deleted before it is used.

推荐答案

来自文档:

当一个 Tempfile 对象被垃圾收集时,或者当 Ruby 解释器退出时,它关联的临时文件会被自动删除.

When a Tempfile object is garbage collected, or when the Ruby interpreter exits, its associated temporary file is automatically deleted.

因此,只要您的 f 在范围内,它就不会被删除.如果您退出 Ruby,它将被删除.如果您仍在使用 Ruby 但 f 已超出范围,则它是不确定的(可能未删除,但不能保证存在,不应使用.)

So, as long as you have your f in scope, it will not be deleted. If you exit Ruby, it will be deleted. If you are still in Ruby but f has fallen out of scope, it is indeterminate (probably not deleted, but not guaranteed to exist, and should not be used.)

更多推荐

Ruby 自动删除临时文件?

本文发布于:2023-07-06 07:40:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047419.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:临时文件   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!