ruby · level 1 · unit 5 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
stops a loop early. skips a turn.
Picture a lift going up a tall building. You ride past each floor, and when you reach yours, you get out. You do not ride to the top. break is getting out: the loop stops straight away.
Some buildings have no floor 13, so the lift skips it and carries on. next is that skip: Ruby drops the rest of this turn and jumps to the next one.
Both usually come with a short if at the end of the line, so they only happen when its condition is true. Any lines after them in the same turn do not run.
10.upto(15) do |floor|
next if floor == 13
break if floor == 15
puts "Ding! Floor #{floor}"
end Floor 13 is skipped by next, and break ends the ride at floor 15.
guess first
What does next do here?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
1.upto(4) do |song|
next if song == 2
puts "Playing song #{song}"
end
your turn
Your turn. Choose what to skip and where to stop.
Type a number to skip in the first blank and a number to stop at in the second. Pick from 1 to 10, then press run.
fix it
Skip burnt cookie 3, but box all the others. Can you fix it?
- Cookies 4 and 5 never get boxed. What happens to the loop when it meets cookie 3?
breakends the whole loop. You only want to skip one turn.- Change
breaktonext, then press run.
nailed it
you can stop a loop whenever you like. :D
breakends the loop straight away.nextskips the rest of one turn.- Pair them with a short
ifat the end of the line.
new words in your collection
- break
- next
This lesson isn’t saved. A free account remembers every lesson you finish.