×

ruby · level 3 · unit 3 · lesson 1

  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

An keeps counting until you say stop.

(1..) is an endless range: 1, 2, 3 and on for ever. Asking it for every item would run until the computer gave up, so you only use methods that stop early. first(3) takes three and stops. hands back the first item its block says yes to, then stops looking.

keeps taking items while its block answers true and stops at the first false. step counts in jumps, so (0..).step(15) gives 0, 15, 30 and so on. Together they answer questions like: when is the first bus after 32 minutes past the hour?

counting = (1..)
p counting.first(3)
puts counting.find { |n| n * n > 50 }
buses = (0..).step(15)
p buses.take_while { |minute| minute < 60 }
puts buses.find { |minute| minute > 32 }

Never call to_a, map or select on an endless range by itself, because they try to visit every number.