Ruby If, Elsif, Else & Unless
Conditions let a program choose what to do. Ruby offers if/elsif/else, its negative twin unless, the ternary operator, and very readable one-line modifiers.
if
battery = 15
if battery < 20
puts "Low battery!"
puts "Please plug in the charger."
endLow battery!
Please plug in the charger.
The condition does not need parentheses, and the body ends with end. Remember the truthiness rule: only false and nil count as false.
if / else
age = 16
if age >= 18
puts "You can vote."
else
puts "You can vote in #{18 - age} years."
endYou can vote in 2 years.
elsif
Use elsif (note the spelling — not else if or elif) for more than two branches:
def grade(score)
if score >= 90
"A"
elsif score >= 80
"B"
elsif score >= 65
"C"
else
"F"
end
end
[95, 83, 70, 40].each { |s| puts "#{s} -> #{grade(s)}" }95 -> A
83 -> B
70 -> C
40 -> F
The conditions are checked from top to bottom, and only the first matching branch runs.
if is an expression
if returns the value of the branch that ran, so you can assign its result directly. The grade method above already relies on this: the value of the last expression in a method is its return value.
hour = 14
greeting = if hour < 12
"Good morning"
elsif hour < 18
"Good afternoon"
else
"Good evening"
end
puts greetingGood afternoon
unless
unless is the opposite of if: the body runs when the condition is false. It reads naturally for negative checks:
logged_in = false
unless logged_in
puts "Please sign in first."
end
items = ["book"]
puts "Cart has items" unless items.empty?Please sign in first.
Cart has items
Tip: Avoid
unless ... elseand avoid negations insideunless(unless !done). They are hard to read — useifinstead.
Modifier form (one-line if/unless)
For a single statement, put the condition after it:
stock = 0
temperature = 38
puts "Sold out" if stock.zero?
puts "Fever!" if temperature > 37.5
puts "All good" unless temperature > 37.5Sold out
Fever!
This style is extremely common in Ruby, especially for guard clauses at the top of a method:
def withdraw(balance, amount)
return "Invalid amount" if amount <= 0
return "Insufficient funds" if amount > balance
"New balance: #{balance - amount}"
end
puts withdraw(100, -5)
puts withdraw(100, 500)
puts withdraw(100, 30)Invalid amount
Insufficient funds
New balance: 70
The ternary operator
condition ? value_if_true : value_if_false is a compact if/else for choosing between two values:
count = 1
puts "You have #{count} #{count == 1 ? 'message' : 'messages'}"
count = 4
puts "You have #{count} #{count == 1 ? 'message' : 'messages'}"You have 1 message
You have 4 messages
Combining conditions
| Need | Write |
|---|---|
| both must be true | a && b |
| at least one true | a || b |
| negate | !a |
| value in a range | (1..10).cover?(n) or n.between?(1, 10) |
| value in a list | %w[jpg png].include?(ext) |
ext = "png"
size_mb = 3
if %w[jpg png gif].include?(ext) && size_mb.between?(0, 5)
puts "Upload accepted"
endUpload accepted
Test yourself
Which keyword adds another condition to an if?
else ifelifelsifelseif
When does puts "x" unless ready print?
- When
readyis truthy - When
readyis false or nil - Always
- Never
What does if 0 then "yes" else "no" end return?
- "yes"
- "no"
- nil
- An error