×

ruby · level 3 · unit 3 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A lazy reads a file only as far as it needs.

Real log files can be gigabytes long. File.read loads the whole thing into memory first. can it instead: with no block it hands back an enumerator that reads one more line each time it is asked. Add .lazy and you have a pipeline, a chain of steps each line flows through.

Because the pipeline is lazy, first(2) stops reading the moment two matching lines have come through, and the rest of the file is never touched. Here the program writes a small log with File.write, then finds the first two errors.

File.write("server.log", "INFO start\nERROR disk full\nINFO retry\nERROR timeout\nERROR crash\n")
errors = File.foreach("server.log").lazy
  .select { |line| line.include?("ERROR") }
  .map { |line| line.chomp.sub("ERROR ", "") }
p errors.first(2)

A line that starts with a dot carries on the chain from the line above, which keeps long pipelines readable.