`
Goldice
  • 浏览: 107778 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Ruby之Tempfile

阅读更多

今天又机会尝试了下Ruby的Tempfile库,相比于自己创建临时文件再删除的方法简便了很多。

 

 

require 'tempfile'

tmp = Tempfile.new("tmp")

tmp.path # => /tmp/tmp20110928-12389-8yyc6w 不唯一

tmp.write("This is a tempfile")
tmp.rewind
tmp.read # => "This is a tempfile"

tmp.close
tmp.unlink # => 删除文件

 

 

当程序退出时,Ruby会自动删除临时文件,所以我们不用显式调用unlink来删除文件。但是这是一个好习惯,解释如下:

 

When a Tempfile object is garbage collected, or when the Ruby interpreter
exits, its associated temporary file is automatically deleted. This means
that's it's unnecessary to explicitly delete a Tempfile after use, though it's
good practice to do so: not explicitly deleting unused Tempfiles can
potentially leave behind large amounts of tempfiles on the filesystem until
they're garbage collected. The existance of these temp files can make it
harder to determine a new Tempfile filename.
 
1
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics