Lesson contents

Ruby — Working with Tempfile and blocks

In Ruby, Tempfile.create with a block manages a temporary file. After writing, rewind lets the block read its contents from the beginning.

A simple example

Read back one letter

  1. Start with A
  2. Do this Write, then read
  3. Result A
A file stores the letter between the write and the read.
lesson.rb
require "tempfile"
Tempfile.create("letter") do |file|
  file.write("A")
  file.rewind
  puts file.read
end
Output
A
Advertisements

Sum two lines from a temporary report

Tempfile.create with a block manages cleanup. rewind moves back to the beginning. each_line supplies an enumerator and sum accumulates the integer values.

Morning returns: 4. Afternoon returns: 7. End of day: 11.
Read a two-line count sheet

Morning staff record four returns in a file and afternoon staff record seven on the next line. Read each line as a number and add it to the running total. The day ends with eleven returns.

Run the example

Ruby 2.7 or later. Run these commands from the directory containing the example.

ruby lesson.rb
lesson.rb
require "tempfile"

Tempfile.create("readings") do |report|
  report.write("4\n7\n")
  report.rewind
  total = report.each_line.sum { |line| line.strip.empty? ? 0 : Integer(line) }
  puts total
end
Output
11

The file contains two whole-number readings on separate lines. Reading from the beginning gives 4 and 7, for a total of 11. The example creates its own file, so it can run in a clean working directory.

Try it yourself

Add a third line containing 12.

Check your answer

The new total is 23. This report format assumes valid integer readings. When accepting external input, apply the validation techniques from the preceding lesson.

Ruby language documentation

Related tags

  • Ruby
  • files
  • streams
  • resource management