typestar

Files in Ruby

Writing, rewinding and reading a file line by line.

require "tempfile"

file = Tempfile.new(["notes", ".txt"])
file.write("line one\nline two\nline three\n")
file.rewind

file.each_line { |line| puts line.chomp.upcase }

file.rewind
puts file.read.lines.count

file.close
file.unlink

How it works

  1. Tempfile.new creates a real file that cleans up after itself.
  2. each_line streams the file; chomp drops the newlines.
  3. rewind resets the cursor so the file reads again from the top.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
231
Tokens
67
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 47 seconds.

Type this snippet

Step 1 of 3 in Files & errors, step 25 of 29 in Language basics.

← Previous Next →

Files in other languages