End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
Tempfile.open
# File tmp/rubies/ruby-3.0.5/lib/tempfile.rb, line 312
def open(*args, **kw)
tempfile = new(*args, **kw)
if block_given?
begin
yield(tempfile)
ensure
tempfile.close
end
else
tempfile
end
end
Creates a new Tempfile.
This method is not recommended and exists mostly for backward compatibility. Please use Tempfile.create instead, which avoids the cost of delegation, does not rely on a finalizer, and also unlinks the file when given a block.
Tempfile.open is still appropriate if you need the Tempfile to be unlinked by a finalizer and you cannot explicitly know where in the program the Tempfile can be unlinked safely.
If no block is given, this is a synonym for Tempfile.new.
If a block is given, then a Tempfile object will be constructed, and the block is run with the Tempfile object as argument. The Tempfile object will be automatically closed after the block terminates. However, the file will not be unlinked and needs to be manually unlinked with Tempfile#close! or Tempfile#unlink. The finalizer will try to unlink but should not be relied upon as it can keep the file on the disk much longer than intended. For instance, on CRuby, finalizers can be delayed due to conservative stack scanning and references left in unused memory.
The call returns the value of the block.
In any case, all arguments (*args) will be passed to Tempfile.new.
Tempfile.open('foo', '/home/temp') do |f| # ... do something with f ... end # Equivalent: f = Tempfile.open('foo', '/home/temp') begin # ... do something with f ... ensure f.close end