If, Else, and Unless
Teach your program to make decisions
Real programs need to make decisions. Should this message be shown? Is this player allowed to enter? Ruby handles decisions using conditional statements, and the most common one is if.
The basic if statement
An if statement checks whether something is true, and only runs its code when that condition is true.
age = 12
if age > 10
puts "You are older than ten."
endSince 12 is greater than 10, this program prints "You are older than ten." Every if statement in Ruby must be closed with the word end.
Adding an alternative with else
Often you want something to happen when the condition is false, too. That is what else is for.
age = 8
if age > 10
puts "You are older than ten."
else
puts "You are ten or younger."
endBecause 8 is not greater than 10, this program skips straight to the else section and prints "You are ten or younger."
Checking multiple conditions with elsif
You can check several conditions in a row using elsif, short for "else if." Ruby checks each condition from top to bottom and stops as soon as it finds one that is true.
score = 75
if score >= 90
puts "Grade: A"
elsif score >= 70
puts "Grade: B"
else
puts "Grade: C or below"
endThe friendly opposite: unless
Ruby also offers unless, which runs its code only when a condition is false. It reads almost like plain English and can make certain checks easier to understand.
age = 8
unless age >= 10
puts "You are not yet ten."
endThis is the same as writing if age < 10, but many Ruby programmers find unless reads more naturally for simple negative checks.
A good rule of thumb: reach for unless only for simple conditions. If a check feels confusing with unless, switch back to if with a negative condition instead.
Quick check
Q1 What keyword must close every if statement in Ruby?
Q2 When does an unless block run its code?
Want to save your progress? It's free.
Create a free account