ruby · level 3 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
How many lines get read? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
File.write("visits.log", "home\nshop\nbasket\nhome\nshop\n")
lines_read = 0
pages = File.foreach("visits.log").lazy.map do |line|
lines_read += 1
line.chomp
end
p pages.find { |page| page == "basket" }
puts lines_read
your turn
Your turn. Find the first big orders in a CSV file.
Choose how many pounds makes an order big, from 10 to 60, then choose how many big orders to take, from 1 to 3.
fix it
Ben is on the guest list, but Ruby says no. Fix it.
- Look at the second line of output. What is stuck to the end of each name?
- Every line read from a file keeps its new line, so "Ben\n" is not the same as "Ben".
- Change
linetoline.chompinside themapblock, then press run.
nailed it
you streamed a file through a pipeline. :D
File.foreachstreams a file one line at a time..lazyturns the steps into a pipeline that stops early.chompeach line before you compare it.
new words in your collection
- File.foreach
- stream
- pipeline
This lesson isn’t saved. A free account remembers every lesson you finish.