ruby · level 3 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Enumerator.new builds a that makes values on demand.
Not every sequence lives in an array. Order numbers, Fibonacci numbers and timetable slots can be worked out one at a time. Enumerator.new builds a generator: you write a block that produces values, and the caller pulls as many as it wants with next or first.
The block gets a , usually called y. Each y << value hands one value to whoever is asking, then pauses the block right there until another value is wanted. That is why loop do inside a generator is safe: it only runs as far as someone pulls.
order_numbers = Enumerator.new do |y|
number = 1000
loop do
y << "ORD-#{number}"
number += 1
end
end
puts order_numbers.next
puts order_numbers.next
p order_numbers.first(3) first always starts from the beginning, while next carries on from its own bookmark.
guess first
Traffic lights on demand. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
lights = Enumerator.new do |y|
puts "Starting"
loop do
y << "green"
y << "amber"
y << "red"
end
end
puts lights.next
puts lights.next
your turn
Your turn. Build a raffle ticket generator.
Choose a short prefix of letters, such as R, and a starting number. The generator should hand out two tickets in a row.
fix it
The washing-up rota runs out on day 3. Fix it.
- Days 1 and 2 work, then StopIteration. Why does the rota run out?
- The block pushes Ana and Ben once, then ends. A rota should go round and round.
- Wrap the two
y <<lines inloop doandend, then press run.
nailed it
you built a generator that never runs dry. :D
Enumerator.newbuilds a generator from a block.y << valuehands out a value and pauses the block.- A
loop doinside a generator only runs as far as someone pulls.
new words in your collection
- generator
- yielder
This lesson isn’t saved. A free account remembers every lesson you finish.