×

ruby · level 3 · unit 3 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

makes a chain do only the work it needs.

Normally map and select are : each one works through every item and builds a whole new array before the next step starts. On an endless range that never finishes, and on a million rows it wastes time. Add .lazy and the chain becomes lazy: each item travels through every step on its own.

Nothing happens until something asks for results. first(3) pulls items through one at a time and stops once it has three. to_a finishes a lazy chain too, but only when the chain has an end. Here a counter shows how few numbers the lazy chain touched.

checked = 0
squares = (1..).lazy.map do |n|
  checked += 1
  n * n
end
p squares.select(&:even?).first(3)
puts "Checked #{checked} numbers"

Lazy chains cost a little extra per item, so use them for endless or very long data, not for five items.