ruby · level 3 · unit 3 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
take_while and select look alike. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
scores = [8, 9, 4, 10, 7]
p scores.take_while { |score| score > 5 }
p scores.select { |score| score > 5 }
your turn
Your turn. When will the piggy bank reach its goal?
Choose how many pounds you save each week, from 5 to 50. The endless range tries week after week until the savings reach 200.
fix it
The week number has gone missing. Fix the range.
- The week number is blank. What does
findhand back when nothing matches? - Saving 15 pounds a week takes more than 10 weeks to reach 200, so the range stops too soon.
- Change
(1..10)to the endless range(1..), then press run.
nailed it
you counted to infinity and stopped in time. :D
(1..)is an endless range that counts for ever.first,findandtake_whilestop as soon as they can.- Never ask an endless range for every item.
new words in your collection
- endless range
- find
- take_while
This lesson isn’t saved. A free account remembers every lesson you finish.