Endless lists: Enumerator and lazy
What actually happens when you call each and leave out the block? No error – you get an Enumerator back: an object that can walk through the list and remembers where it currently is. With next you fetch one element after the other, whenever you like:
breakfast = ["bacon", "egg", "toast"]
plate = breakfast.each
p plate
p plate.next
p plate.next
plate.nextEvery next moves on by one. After the last element it's over: a fourth plate.next raises the error StopIteration (“iteration reached an end”) – try it. And that is exactly the error loop catches: loop do … end repeats its block forever, until a break comes – or a StopIteration. Then it simply stops, quietly:
plate = breakfast.each
loop do
puts "Chunky eats #{plate.next}"
end
puts "Plate empty!"Not only each returns an Enumerator without a block – map, select and many others do too. You can hang further methods onto it. The most useful one is with_index: it hands the block the number as well, and unlike each_with_index from lesson 8 it may start at 1 and fits onto any of these methods – map too:
breakfast.each.with_index(1) do |food, nr|
puts "#{nr}. #{food}"
end
breakfast.map.with_index(1) { |food, nr| food * nr }Bacon once, egg twice, toast three times. And now it gets endless: cycle goes round and round a list – after the last element the first one again, on and on. Handy for anything where you take turns – who does the dishes today? An endless Enumerator must never be walked through completely; an each on it would never stop. You take what you need: first(5) or take(5) fetch the first five, and zip takes exactly as many as the other list is long:
dishes = ["Chunky", "Kaz", "Isi"].cycle
p dishes.first(5)
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
days.zip(dishes).map { |day, who| "#{day}: #{who}" }You build endless lists of your own with Enumerator.new. Its block gets a helper, usually called y, and y << value hands out the next value – much like yield from lesson 23. The block may even hold an endless loop: it only runs as far as someone wants values, and then waits:
squares = Enumerator.new do |y|
n = 1
loop do
y << n * n
n += 1
end
end
squares.first(10)first(10) wanted ten values, so the block handed out ten values – not a single one more. A classic to build yourself is the Fibonacci numbers: each is the sum of the two before it, 0, 1, 1, 2, 3, 5, 8 … a, b = b, a + b moves both on at once. And take_while takes values as long as they meet a condition, and stops at the first one that doesn't. A select, on the other hand, would go on searching an endless list forever:
fibonacci = Enumerator.new do |y|
a, b = 0, 1
loop do
y << a
a, b = b, a + b
end
end
p fibonacci.first(10)
fibonacci.take_while { |f| f < 100 }And if you do want to transform and sift an endless list? Normally every method in a chain works through the whole list before the next one gets its turn – for an endless list that would mean: never. lazy turns this around: each element travels through the whole chain on its own, and only the first at the end says when to stop. Watch the order in which things get computed:
eager = (1..4).map { |n| puts "compute #{n}"; n * n }
p eager.first(2)
sleepy = (1..4).lazy.map { |n| puts "compute #{n}"; n * n }
sleepy.first(2)The eager chain computes all four numbers although only two are needed; the lazy one exactly two. With (1..) – a range without an end – instead of (1..4), the eager one would never finish, and the cell would run until you reload the page (⚡ Live stops it after a second, ▶ doesn't). Better not try it. The lazy one, though, copes with the endless just fine – here with all the numbers from 1 and with the square numbers from above: which of them read the same backwards, like the palindromes from lesson 31?
sevens = (1..).lazy.select { |n| n % 7 == 0 }
p sevens.first(5)
mirrored = squares.lazy.select { |s| s.to_s == s.to_s.reverse }
mirrored.first(6)A rule of thumb: an Enumerator is a list whose values only come into being when someone asks for them – that's why it may be endless. Never ask an endless list for everything (each, map, select, to_a, sum), only for as much as you need: with next, first, take_while or zip. And if you want to transform or sift along the way, switch on lazy first.
triangles with Enumerator.new: triangles.first(6) should give [1, 3, 6, 10, 15, 21].# triangles = Enumerator.new do |y|
# ... # start with 0 strips and row 1,
# ... # then forever: add the row, hand out the sum, next row
# end
# triangles.first(6)long_journeys(count, steps), which uses lazy to find the first count start numbers from 1 on whose journey takes more than steps steps: long_journeys(3, 100) gives [27, 31, 41]. The step counter is best written as a small method of its own, journey_length(n).# def journey_length(n)
# ... # count the Collatz steps from n down to 1
# end
# def long_journeys(count, steps)
# ... # (1..).lazy ... the first count start numbers
# ... # whose journey takes more than steps steps
# end
# long_journeys(3, 100)