TExcelTAD
Home › Ruby › Ruby If, Elsif, Else & Unless

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

ruby · try it yourself
battery = 15

if battery < 20
  puts "Low battery!"
  puts "Please plug in the charger."
end
Low 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

ruby · try it yourself
age = 16

if age >= 18
  puts "You can vote."
else
  puts "You can vote in #{18 - age} years."
end
You can vote in 2 years.

elsif

Use elsif (note the spelling — not else if or elif) for more than two branches:

ruby · try it yourself
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.

ruby · try it yourself
hour = 14
greeting = if hour < 12
  "Good morning"
elsif hour < 18
  "Good afternoon"
else
  "Good evening"
end
puts greeting
Good afternoon

unless

unless is the opposite of if: the body runs when the condition is false. It reads naturally for negative checks:

ruby · try it yourself
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 ... else and avoid negations inside unless (unless !done). They are hard to read — use if instead.

Modifier form (one-line if/unless)

For a single statement, put the condition after it:

ruby · try it yourself
stock = 0
temperature = 38

puts "Sold out" if stock.zero?
puts "Fever!" if temperature > 37.5
puts "All good" unless temperature > 37.5
Sold out
Fever!

This style is extremely common in Ruby, especially for guard clauses at the top of a method:

ruby · try it yourself
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:

ruby · try it yourself
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)
ruby · try it yourself
ext = "png"
size_mb = 3
if %w[jpg png gif].include?(ext) && size_mb.between?(0, 5)
  puts "Upload accepted"
end
Upload accepted

Test yourself

Which keyword adds another condition to an if?

  1. else if
  2. elif
  3. elsif
  4. elseif

When does puts "x" unless ready print?

  1. When ready is truthy
  2. When ready is false or nil
  3. Always
  4. Never

What does if 0 then "yes" else "no" end return?

  1. "yes"
  2. "no"
  3. nil
  4. An error