Teach programs to decide: if, elsif, unless and case turn true/false questions into different paths.
The big picture
Code that chooses
So far every line ran. Control flow lets your program pick a path: run this, skip that, depending on the answers to true/false questions.
1
if / elsif / else
Ruby checks each condition top to bottom and runs the first true branch — exactly one.
2
unless
Reads like English: run this unless the condition is true.
3
case / when
Compare one value against a list of options and run the matching branch.
4
Conditions are questions
Every condition boils down to true or false — comparisons and && || ! build them.
Code that chooses
if / elsif / else1Ruby checks each condition top to bottom and runs the first true branch — exactly one.
unless2Reads like English: run this unless the condition is true.
case / when3Compare one value against a list of options and run the matching branch.
Conditions are questions4Every condition boils down to true or false — comparisons and && || ! build them.
4 building blocks make up Code that chooses
Watch it run
Branches in action
Two programs: one climbs the if/elsif ladder, one tries unless and case/when.
grade.rb
1score =78
2
3if score >=90
4puts"A"
5elsif score >=80
6puts"B"
7elsif score >=70
8puts"C"
9else
10puts"Keep trying!"
11end
12
13puts"Done"
main
score gets 78.
Memory
score= 78
Console
output appears as the program runs…
Step 1/6
Visualize
Walking the if ladder
Each diamond is a question. Ruby stops asking as soon as one answer is yes.
process decision input / output start / end
Practice
Match the decision keywords
Click a keyword, then click its job to lock the pair.
6 conceptsTap a card to expand
?if / elsif / elsedrops into place
?unlessdrops into place
?case / whendrops into place
?&&drops into place
?||drops into place
?!drops into place
Challenge
Predict the output
Three kinds of branches, one number — read each question carefully.
choices.rb
1n =12
2
3if n >10&& n <20
4puts"teen zone"
5end
6
7unless n ==12
8puts"not twelve"
9end
10
11case n
12when1,2,3
13puts"small"
14else
15puts"bigger"
16end
Your predicted output — one line per console line
Hint: 12 > 10 and 12 < 20 are both true, so && lets the first branch through. unless runs only when the condition is false — 12 == 12 is true, so nothing prints. And 12 is not in 1, 2, 3, so the else branch catches it.
Recap
Key takeaways
Key takeaways5 takeaways
01
if/elsif checks top to bottom and runs exactly one branch.
02
unless runs when the condition is false — the opposite of if.
03
case/when compares one value against many options.