Iterators and Blocks

Iterators and Blocks in Ruby: --- A bottling line runs a belt past a single station where one inspector works.


The Analogy: The Conveyor Belt And The Inspector's Station

A bottling line runs a belt past a single station where one inspector works. The belt owns the movement completely: it decides what comes past, in what order, how fast, and when there is nothing left. The inspector never touches the belt controls. She has one job, written on a card clipped to the station, and she does that job to each item as it arrives. Swap the card and the same belt does something entirely different without a single change to the belt itself.

That division is the whole idea behind a Ruby block. The collection owns the iteration -- each knows how to walk an Array, a Hash, a file, a range of dates -- and your block is the card clipped to the station. You are not writing a loop that pulls items out of a container; you are handing a small piece of work to a container that already knows how to walk itself. This is why Ruby code so rarely contains an index variable, and why the same three lines read the same whether they are walking six bottles or six million rows.

Different cards mean different stations. One card says stamp a label on every item and put it back on the belt, and the belt comes out the far end the same length as it went in: that is map. One says push anything under a certain size into the bin at your feet, and what continues is shorter: select and reject. One says keep a running total on the clipboard and only tell me the number at the end: reduce and each_with_object. One says stop the belt the instant you see a red cap: find. The card can also remember things between items, because it can see the notepad the supervisor left on the bench beside the station, which is what a block being a closure over its enclosing variables amounts to.

The failure modes are the ones you would expect on a real line. An inspector who reaches into the belt mechanism and removes links while items are still moving will drop things, which is exactly what happens when you delete from an Array inside each and the iteration quietly skips elements. An inspector who takes each item off the belt, does something to it, and puts nothing back leaves the next station with nothing to do; that is each used where map was needed, and the giveaway is that you got the original collection back instead of the transformed one. An inspector who alters items in place rather than producing new ones invalidates every record the earlier stations wrote down. And a belt fed from a hopper that never empties will run until the shift ends unless the card says stop after three, which is why an unbounded sequence needs first, take, find or lazy rather than map.


Syntax or Core Structure

One belt, several stations. Every method below hands items to a block; the difference between them is entirely in what they hand back to you.

# belt.rb -- one belt, several stations, no station touching the belt controls.

BOTTLES = [500, 330, 500, 750, 330, 500]

# each hands one item at a time to the block.
BOTTLES.each_with_index do |ml, i|
  puts "station 1 item #{i} sees #{ml}ml"
end

# and it hands you back the collection itself, not the block's results.
returned = BOTTLES.each { |ml| ml }
puts "each returned the same object: #{returned.equal?(BOTTLES)}"

# map builds a new collection of the same length.
labels = BOTTLES.map { |ml| "#{ml}ml" }
puts labels.join(", ")
puts "sizes #{BOTTLES.size} -> #{labels.size}"

# select keeps, reject discards, and each gives you a new Array.
large = BOTTLES.select { |ml| ml >= 500 }
small = BOTTLES.reject { |ml| ml >= 500 }
puts "large #{large.inspect}"
puts "small #{small.inspect}"

# find stops the belt at the first item the block admits.
seen = 0
found = BOTTLES.find do |ml|
  seen += 1
  ml == 750
end
puts "found #{found} after #{seen} items"

# reduce carries a value from item to item.
total = BOTTLES.reduce(0) { |sum, ml| sum + ml }
puts "total #{total}ml in #{BOTTLES.size} bottles"

# each_with_object carries a container instead of a value.
tally = BOTTLES.each_with_object(Hash.new(0)) { |ml, counts| counts[ml] += 1 }
tally.keys.sort.each { |ml| puts "#{ml}ml x#{tally[ml]}" }

# An Integer and a Range are belts too.
3.times { |i| puts "pass #{i}" }
(1..3).each { |n| puts "step #{n}" }

Output:

station 1 item 0 sees 500ml
station 1 item 1 sees 330ml
station 1 item 2 sees 500ml
station 1 item 3 sees 750ml
station 1 item 4 sees 330ml
station 1 item 5 sees 500ml
each returned the same object: true
500ml, 330ml, 500ml, 750ml, 330ml, 500ml
sizes 6 -> 6
large [500, 500, 750, 500]
small [330, 330]
found 750 after 4 items
total 2910ml in 6 bottles
330ml x2
500ml x3
750ml x1
pass 0
pass 1
pass 2
step 1
step 2
step 3

The third block is the one beginners lose an hour to. each hands back the receiver, the very same object, which is why returned.equal?(BOTTLES) is true and why assigning the result of an each is almost always a mistake. If you want the block's results, the method you want is map, and map guarantees one result per item: six bottles in, six labels out, every time.

found 750 after 4 items is the other line worth staring at. find did not walk the whole belt. It stopped the moment the block admitted an item, four items in, which the seen counter proves. That early stop is not an optimisation you asked for, it is part of what find means, and the same is true of any?, all?, none? and take_while. Methods that must inspect everything, like map and select, cannot do this and never pretend to.


Technical Depth: Who Drives, And What Comes Back

Every Method Hands Back Something Different

MethodWhat it hands the blockWhat it hands back to you
eachone elementthe receiver, unchanged
mapone elementa new Array of the block's results, same length
selectone elementa new Array of the elements the block admitted
rejectone elementa new Array of the elements the block refused
findone element, stopping at the first admittedthat element, or nil
reducethe running value and one elementthe final running value
each_with_objectone element and the containerthe container
flat_mapone elementa new Array with one level of nesting flattened
group_byone elementa Hash from each block result to the matching elements
partitionone elementtwo Arrays, the admitted ones first
tallynothing, it takes no blocka Hash counting how often each element appears

The Block Is An Argument, Not A Loop Body

A block is passed to a method the way any other argument is, and the method decides when and how often to call it. yield is how a method calls the block it was given, block_given? asks whether there was one, and returning an Enumerator when there was not is the convention every built-in iterator follows.

module Belt
  def self.each_pair(list)
    return to_enum(:each_pair, list) unless block_given?

    i = 0
    while i < list.size - 1
      yield(list[i], list[i + 1])
      i += 1
    end
    list
  end
end

Belt.each_pair([500, 330, 750]) { |a, b| puts "#{a} then #{b}" }

enum = Belt.each_pair([500, 330, 750])
puts enum.class
puts enum.to_a.inspect

Output:

500 then 330
330 then 750
Enumerator
[[500, 330], [330, 750]]

That one return to_enum line is what makes the method a first class member of the family. Without a block the caller gets an Enumerator, which means each_pair(list).to_a, each_pair(list).with_index and each_pair(list).lazy all work without you writing another line.

Blocks, Procs, And Lambdas

KindHow you make oneExtra or missing argumentsWhat return inside it does
a blockbraces or do and end after a callignored, or filled in with nilreturns from the enclosing method
a Procproc or Proc.newignored, or filled in with nilreturns from the enclosing method
a lambdalambda or the arrow formraises ArgumentErrorreturns from the lambda alone
a method objectmethod(:name)raises ArgumentErrorreturns from that method
shape_proc = proc { |a, b| "#{a.inspect} #{b.inspect}" }
shape_lambda = ->(a, b) { "#{a.inspect} #{b.inspect}" }

puts shape_proc.call(1)
puts shape_proc.call(1, 2, 3)
puts shape_lambda.call(1, 2)

begin
  shape_lambda.call(1)
rescue ArgumentError => e
  puts "lambda refused: #{e.class}"
end

puts shape_proc.lambda?
puts shape_lambda.lambda?
puts shape_proc.arity
puts shape_lambda.arity

Output:

1 nil
1 2
1 2
lambda refused: ArgumentError
false
true
2
2

A proc is lenient about arity and a lambda is strict, which is the practical difference you will feel first. Both report an arity of 2, so arity tells you what the thing was written to accept, not what it will tolerate. The return column matters more but bites less often: a return inside a block or proc returns from the method that created it, so a proc called after that method has finished raises LocalJumpError, while a lambda's return only ever leaves the lambda.

Enumerable Is Built From One Method

Define each and include Enumerable, and your class inherits roughly fifty methods it never mentions. This is the single best return on four lines of code anywhere in the standard library.

class Crate
  include Enumerable

  def initialize(*bottles)
    @bottles = bottles
  end

  def each(&block)
    return to_enum(:each) unless block_given?

    @bottles.each(&block)
    self
  end
end

crate = Crate.new(500, 330, 750, 330)
puts crate.sort.inspect
puts crate.max
puts crate.include?(750)
puts crate.each_slice(2).to_a.inspect
puts crate.tally.sort.inspect
puts crate.sum
puts crate.first(2).inspect

Output:

[330, 330, 500, 750]
750
true
[[500, 330], [750, 330]]
[[330, 2], [500, 1], [750, 1]]
1910
[500, 330]

Crate never defines sort, max, include?, each_slice, tally, sum or first. Every one of them is Enumerable calling the each you wrote. The &block parameter is how you accept a block as an ordinary named argument and hand it straight on to another method, and tally.sort is printed rather than tally itself so the output is an Array of pairs whose textual form does not change between Ruby versions.

A Belt With No End

volumes = (1..Float::INFINITY).lazy.map { |n| n * 30 }
puts volumes.select { |ml| ml % 100 == 0 }.first(3).inspect

squares = (1..Float::INFINITY).lazy.map { |n| n * n }
puts squares.first(4).inspect

count = 0
(1..Float::INFINITY).each do |n|
  count += 1
  break if n == 5
end
puts count

Output:

[300, 600, 900]
[1, 4, 9, 16]
5

Without lazy, the first line would try to multiply every natural number by thirty before selecting anything, and the program would never print. lazy turns the chain inside out: one element is pulled through map and select at a time, and pulling stops the moment first(3) has what it asked for. The counter at the bottom shows the blunter tool, break, which leaves the iterator immediately and can hand back a value if you give it one.


Real World Example: The Fill Report From One Shift

Ten bottles came off the line, each with a nominal size printed on the label and an actual measured fill. The report below is three different kinds of accumulation over the same belt: grouped statistics, a two way split, and a running total per size.

# fill_report.rb -- what came off the belt, and what the belt got wrong.

FILLS = <<~ROWS
  0602 500 498
  0604 500 503
  0607 330 331
  0611 750 742
  0615 500 499
  0618 330 328
  0622 750 751
  0626 500 486
  0631 330 330
  0634 750 748
ROWS

TOLERANCE = 5

Fill = Struct.new(:minute, :nominal, :actual) do
  def deviation
    actual - nominal
  end

  def under?(tolerance)
    deviation < -tolerance
  end

  def clock
    format("%02d:%02d", minute / 60, minute % 60)
  end
end

def parse(text)
  text.lines.map do |line|
    hhmm, nominal, actual = line.split
    Fill.new(hhmm[0, 2].to_i * 60 + hhmm[2, 2].to_i, nominal.to_i, actual.to_i)
  end
end

fills = parse(FILLS)
puts "fills: #{fills.size}"

by_size = fills.group_by(&:nominal)
by_size.keys.sort.each do |nominal|
  batch = by_size[nominal]
  worst = batch.min_by(&:deviation)
  puts format("  %3dml  n=%d  poured=%5d  worst=%+d at %s",
              nominal, batch.size, batch.sum(&:actual), worst.deviation, worst.clock)
end

under, within = fills.partition { |f| f.under?(TOLERANCE) }
puts "under by more than #{TOLERANCE}ml: #{under.size}"
under.each do |f|
  puts format("  %s  %3dml nominal, %3dml actual, %+dml", f.clock, f.nominal, f.actual, f.deviation)
end
puts "within tolerance: #{within.size}"

drift = fills.each_with_object(Hash.new(0)) { |f, h| h[f.nominal] += f.deviation }
drift.keys.sort.each { |nominal| puts "  #{nominal}ml net #{drift[nominal]}ml" }

poured = fills.sum(&:actual)
intended = fills.sum(&:nominal)
puts "poured #{poured}ml against #{intended}ml intended, net #{poured - intended}ml"

Output:

fills: 10
  330ml  n=3  poured=  989  worst=-2 at 06:18
  500ml  n=4  poured= 1986  worst=-14 at 06:26
  750ml  n=3  poured= 2241  worst=-8 at 06:11
under by more than 5ml: 2
  06:11  750ml nominal, 742ml actual, -8ml
  06:26  500ml nominal, 486ml actual, -14ml
within tolerance: 8
  330ml net -1ml
  500ml net -14ml
  750ml net -9ml
poured 5216ml against 5240ml intended, net -24ml

Three accumulations, three different tools. group_by(&:nominal) builds a Hash from each nominal size to the Array of fills that had it, which is the right shape when you want per-group statistics. partition makes one pass and hands back two Arrays, the failures and the rest, which beats calling select and then reject with the negated condition and hoping the two conditions stay in step. And each_with_object(Hash.new(0)) accumulates into a container, where reduce would have forced the block to hand the Hash back on every iteration. The Struct.new block is worth noting too: a Struct can carry behaviour, so deviation, under? and clock live with the data instead of being loose methods that take a fill as an argument.

Nothing in the report leaves its order to chance. by_size.keys.sort is what makes the three size lines come out 330, 500, 750 every run rather than in whatever order the sizes happened to first appear in the log, and partition preserves the original order of the belt, so the two underfills are listed in the order they happened. min_by(&:deviation) hands back the whole Fill rather than just the number, which is why the line can print both the deviation and the time it happened at; min would have given us a number with no address.

The numbers themselves are all integers, deliberately. Millilitres are counted in whole units, so deviation is exact, the net drift figures add up by inspection, and the final line can be checked by hand: the ten deviations are minus two, plus three, plus one, minus eight, minus one, minus two, plus one, minus fourteen, zero and minus two, which sum to minus twenty four, exactly the gap between 5216ml poured and 5240ml intended.

Now the flaw, and it is a real one rather than a rough edge. under? asks only whether the deviation is below the negative tolerance, so the report is structurally blind to overfilling. A bottle at 560ml against a 500ml label is counted as within tolerance and lands in the same bucket as a perfect pour, even though giving away sixty millilitres a bottle is the expensive direction for the company and a mislabelled volume is the direction a regulator cares about. Today's data hides this, because every overfill happens to be small, which is exactly how a bug like this survives a code review. The net drift figure has the same shape of problem: it adds a minus fourteen to a plus three and reports minus eleven, so a line that alternates wild overfills and underfills reports a healthy net near zero while producing nothing but rejects. A mean absolute deviation would say what the net cannot. Two smaller limits round it out: TOLERANCE is a single number for all three sizes, when five millilitres means something quite different on a 330 than on a 750; and min_by picks an arbitrary winner when two fills tie for worst, without saying that it did.


Common Mistakes

  1. Using each where you needed map. each hands back the receiver, not the results of the block, so doubled = list.each { |n| n * 2 } leaves doubled equal to the original list and throws every computed value away. The code looks like it works because doubled is an Array of the right length. Reach for map the moment the block's return value matters, and keep each for the cases where you want the side effect and nothing else.
  1. Mutating a collection while iterating over it. Calling delete or << on an Array inside its own each shifts the indices out from under the iterator, so elements get skipped or visited twice with no error raised. Build the answer with reject, select or map and then assign, or collect the doomed items in a separate Array and remove them after the loop has finished.
  1. Expecting map to filter. A block that ends in next if still contributes an entry to the result, and that entry is nil, so list.map { |n| n if n > 100 } gives you an Array padded with nils rather than a shorter Array. Use select to filter, map to transform, and filter_map when you genuinely want both in one pass.
  1. Forgetting that a block's last expression is its return value. Writing map { |f| puts f.name } produces an Array of nil, because puts returns nil. Any time a map result comes back full of nils, look at the final line of the block rather than at the collection.
  1. Reaching for reduce when the accumulator is a container. With reduce the block must hand the accumulator back every single time, so reduce(Hash.new(0)) { |h, x| h[x] += 1 } breaks: h[x] += 1 evaluates to the new count, and that Integer becomes the accumulator for the next iteration. Use each_with_object, which ignores the block's return value and passes the same object through, or make the last line of the reduce block h on purpose.
  1. Relying on the iteration order of a Hash you built by grouping or tallying. group_by and tally return Hashes ordered by first appearance in the source data, which means the order of your printed report is decided by the order of the input file. Call .keys.sort or .sort before printing anything you intend to compare between runs.
  1. Iterating an infinite range without lazy. (1..Float::INFINITY).map { |n| n * 30 }.first(3) never gets to first, because map tries to build the whole Array first and the program hangs with no output. Insert lazy before the chain and the elements are pulled one at a time, only as many as first(3) actually needs.
  1. Treating a proc as if it were a lambda. A proc accepts the wrong number of arguments without complaint, filling the gaps with nil and discarding extras, and a bare return inside one returns from the enclosing method rather than from the proc. That combination turns an argument-count bug into a silently wrong value and a stray return into an early exit from the caller. Use lambda or the -> arrow when you want the strict arity check and a local return.
  1. Calling a method that yields without checking block_given?. A method whose body reaches yield with no block attached raises LocalJumpError, which is a confusing failure to read at a call site that looks perfectly ordinary. Guard with return to_enum(:each) unless block_given? so the blockless call hands back an Enumerator instead, which is what every built-in iterator does.

Best Practices

  • Pick the method whose name states the intent: each for effects, map for a new collection of the same length, select and reject for a subset, find for the first match, sum and count for a number. A reader who trusts the verb does not have to read the block.
  • Return an Enumerator from your own iterators when no block is given. One return to_enum(:each) unless block_given? line makes your object work with with_index, each_slice and lazy for free.
  • Include Enumerable and define each rather than hand-writing map, select, sort_by and sum on your own class. One correct each buys the whole module, and the methods you would have written by hand are the ones most likely to disagree with each other.
  • Use each_with_object when you are filling a container and reduce when you are folding to a single value. The distinction is not stylistic: each_with_object cannot be broken by a block that forgets to hand the accumulator back.
  • Sort before you print. Any report built from group_by, tally or a plain Hash should go through .keys.sort or .sort, so the output is a function of the data rather than of the order it arrived in.
  • Give ties an explicit tiebreaker. sort_by { |x| [-x.count, x.name] } is reproducible where max_by(&:count) picks an arbitrary winner among equals, and reproducibility is what lets you diff two runs.
  • Add lazy when the source is unbounded or expensive and you only need a prefix of it. It changes the chain from build-everything-then-take to take-only-what-is-asked-for, without changing a single method name in the chain.
  • Prefer a lambda over a proc for anything you store and call later. The strict arity check turns a wrong-argument-count mistake into an immediate ArgumentError at the call site instead of a nil that surfaces three methods away.

Practice Exercises

  1. Rebuild the tally without tally. Take the BOTTLES Array from the first example and produce the same size-to-count Hash three ways: with each_with_object(Hash.new(0)), with group_by followed by transform_values(&:size), and with reduce where the block ends in the accumulator on purpose. Print all three with .sort.inspect and assert that the three results are equal.
  1. Add each_run to the crate. Extend the Crate class with an each_run method that yields consecutive equal values as one Array, so [330, 330, 500, 750] yields [330, 330], then [500], then [750]. Return to_enum(:each_run) when no block is given, then confirm that crate.each_run.to_a.size is 3 and that crate.each_run.map(&:size) gives [2, 1, 1].
  1. Make the fill report catch overfills. Change under? into an out_of_tolerance? method that tests the absolute deviation, split the fills three ways with group_by on the sign of the deviation instead of partition, and add a mean absolute deviation per nominal size alongside the net drift. Feed it a row like 0640 500 560 and show that the old report called that bottle acceptable while the new one does not.
  1. Measure what lazy actually skips. Write a method expensive(n) that increments a global counter and returns n * n, then run (1..20).map { |n| expensive(n) }.first(3) and (1..20).lazy.map { |n| expensive(n) }.first(3), printing the counter after each. Explain the two numbers you get, and then predict the counter for the lazy chain with select { |sq| sq.even? }.first(3) before you run it.