Ruby Tempfile.create
Tempfile.create with a block supplies an open temporary file and arranges cleanup when the block exits.
A simple example
Tempfile.create
- Start with A new temporary file
- Do this Write A and rewind to read
- Result A
Syntax
Tempfile.create('report') { |file| ... }
Run this example in Ruby
Save the program as lesson.rb. Use Ruby 2.6 or later.
ruby lesson.rb
Stage a report in a temporary file
A job needs scratch storage while preparing its final report. Use a temporary stream or file to stage the records, then close it once the contents have been counted or passed onward.
require 'tempfile'
path = Tempfile.create('report') do |file|
file.puts 'ready'
file.rewind
puts file.gets.chomp
file.path
end
puts File.exist?(path)
ready false
Rewind after writing to read from the beginning. The example checks the path after the block to confirm cleanup without depending on the random file name.
Ruby documentation for Tempfile.create
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Save the note and read it back before the desk closes. Which characters are recovered?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. Save the note and read it back before the desk closes. Which characters are recovered?