Ruby 自动删除临时文件? [英] Ruby auto deleting temp file?

查看:54
本文介绍了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 自动删除临时文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆