Library contents

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

  1. Start with A new temporary file
  2. Do this Write A and rewind to read
  3. Result A
The temporary file holds the letter while the block is using it.

Syntax

Ruby 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.

First output lineready
lesson.rb
require 'tempfile'

path = Tempfile.create('report') do |file|
  file.puts 'ready'
  file.rewind
  puts file.gets.chomp
  file.path
end
puts File.exist?(path)
Output
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

Advertisements

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?

GivenFile contents “clay”
Worked resultclay

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?

GivenFile contents “ring bell”
Worked resultring bell