ruby notes

Small things I keep relearning about Ruby.

When lazy is worth it

Enumerable#lazy turns a chain of map and select into a pipeline that processes one element at a time. That matters when the source is huge or infinite:

File.foreach("access.log").lazy
    .select { |l| l.include?(" 500 ") }
    .map    { |l| l.split.first }
    .first(20)

Without lazy, this would read the entire file into intermediate arrays before taking twenty lines.

On small in-memory arrays, though, each lazy step adds a block call and an enumerator object. In a quick benchmark on a 1,000-element array, the eager version was roughly twice as fast. My rule now: reach for lazy when the input is streamed or unbounded, or when you stop early with first.