Menu
Coddy logo textTech

Unless Statement

Part of the Fundamentals section of Coddy's Ruby journey — lesson 25 of 88.

Ruby offers a unique way to express conditions when you want to run code only if something is not true. The unless statement is essentially the opposite of if.

With if, code runs when the condition is true. With unless, code runs when the condition is false:

logged_in = false

unless logged_in
  puts "Please log in to continue"
end

This is equivalent to writing if !logged_in, but unless often reads more naturally. Think of it as "do this unless that condition is true."

You can also use unless with else:

age = 20

unless age < 18
  puts "Access granted"
else
  puts "Access denied"
end

However, when you need an else block, using if is usually clearer. The unless statement shines when you have a simple negative condition without an alternative path. Choose whichever makes your code easier to read at a glance.

challenge icon

Challenge

Easy

You are provided with the following variables:

has_ticket = false
is_vip = true
items_in_cart = 0
battery_level = 15
is_charging = false

Use unless statements to evaluate each scenario below. Print the specified message only when the condition is false (which is when unless executes its block).

  1. Unless has_ticket is true, print Please purchase a ticket
  2. Unless is_vip is true, print VIP access required
  3. Unless items_in_cart is greater than 0, print Your cart is empty
  4. Unless battery_level is greater than 20, print Low battery warning
  5. Unless is_charging is true or battery_level is greater than 50, print Please charge your device

Each message should appear on its own line. Only print messages for conditions that trigger the unless block.

Cheat sheet

The unless statement runs code when a condition is false, making it the opposite of if:

logged_in = false

unless logged_in
  puts "Please log in to continue"
end

This is equivalent to if !logged_in, but often reads more naturally.

You can use unless with else:

age = 20

unless age < 18
  puts "Access granted"
else
  puts "Access denied"
end

However, unless is best used for simple negative conditions without an else block. When you need an alternative path, if is usually clearer.

Try it yourself

# Variables are already defined for you
has_ticket = false
is_vip = true
items_in_cart = 0
battery_level = 15
is_charging = false

# TODO: Write your code below
# Use unless statements to check each condition and print the appropriate message
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals