Ruby之Tempfile _Ruby_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > Ruby > Ruby之Tempfile

Ruby之Tempfile

 2011/9/29 8:03:58  Goldice  http://jdoc.iteye.com  我要评论(0)
  • 摘要:今天又机会尝试了下Ruby的Tempfile库,相比于自己创建临时文件再删除的方法简便了很多。require'tempfile'tmp=Tempfile.new("tmp")tmp.path#=>/tmp/tmp20110928-12389-8yyc6w不唯一tmp.write("Thisisatempfile")tmp.rewindtmp.read#=>"Thisisatempfile"tmp.closetmp.unlink#=>删除文件当程序退出时
  • 标签:

今天又机会尝试了下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.
?
  • 相关文章
发表评论
用户名: 匿名