ruby · level 1 · unit 5 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
repeats a job as often as you ask.
Imagine skipping with a rope. You do not write down every jump. You say jump 10 times. A works the same way: write the lines once, and Ruby repeats them. 3.times do means do this 3 times.
The lines between do and end are a , the bundle of code that gets repeated. Put a name between two bars, like |lap|, and it holds which go it is: 0, then 1, then 2.
To count from 1 instead, use : 1.upto(5) do |number| counts 1, 2, 3, 4 and 5. Lines after the end run once, after the loop has finished.
3.times do |lap|
puts "Lap #{lap}"
end
puts "Finished!" Ruby counts from 0, so 3 laps are numbered 0, 1 and 2.
guess first
Where does the counting stop?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
2.upto(5) do |number|
puts number
end
your turn
Your turn. Make a cheer repeat.
Pick how many times to cheer, from 2 to 10, and type it in the first blank. Type your own cheer between the quotes, then press run.
fix it
The frog should go Ribbit, then Splash!, three times over. Fix it.
- Splash! only shows once. Is that line inside the block or after it?
- Only the lines between
doandendrepeat. Line 4 comes after theend. - Move puts "Splash!" up, above the
end, then press run.
nailed it
you made the computer repeat itself. :D
3.times dorepeats a block 3 times.- The block is every line between
doandend. |lap|counts from 0.uptocounts from where you say.
new words in your collection
- loop
- times
- block
- upto
This lesson isn’t saved. A free account remembers every lesson you finish.