ruby · level 1 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Put an if inside a loop to check every number.
Picture a postie walking down a street. At every door they ask the same question: does this house get a letter? Put an if inside a loop and Ruby can ask a question on every turn too.
asks whether a number is even, and asks whether it is odd. When an if guards one short line, Ruby lets you put it at the end: puts house if house.even?.
To count matches, make a variable set to 0 before the loop. Each time the check is true, add 1 to it. Show it after the loop, once the counting is done.
1.upto(6) do |house|
if house.even?
puts "Letter for house #{house}"
end
end The if sits inside the block, so it runs once for every house.
guess first
How many claps? Count before you run.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
claps = 0
1.upto(5) do |beat|
claps = claps + 1 if beat.odd?
end
puts claps
your turn
Your turn. Hand out free stickers.
Choose which visitors win a sticker by typing a number from 2 to 10. Type 5 and every 5th visitor wins. Run it to see how many of 30 visitors get one.
fix it
The street has 10 houses, and even ones are on the left. Fix the count.
- The street has houses 1 to 10. Which house does the loop never visit?
uptostops at the number in its brackets, and here that is 9. House 10 is even, so it is missed.- Change 1.upto(9) to 1.upto(10), then press run.
nailed it
your loops can make choices now. :D
- An
ifinside a loop checks every turn. .even?and.odd?givetrueorfalse.- Start a counter at 0 before the loop.
new words in your collection
- even?
- odd?
This lesson isn’t saved. A free account remembers every lesson you finish.