← Back to Ruby Course | Chapter 6: Control Flow | Lesson 2 of 7

unless

unless is the opposite of if: it runs the code only when the condition is false. It is like saying 'unless it is raining, we go outside'.

In this page:

  1. unless
Syntax
ruby
unless condition
  # runs when condition is false
else
  # otherwise
end

unless

unless condition runs its block only when the condition is falsy, acting as the inverse of if. It's used when the negated phrasing reads more naturally than if !condition.

unless also has a trailing modifier form, like puts "error" unless valid.

Note: unless should generally only be used with simple conditions -- avoid pairing it with else, which is often confusing to read.

Example: unless

markup
logged_in = false

unless logged_in
  puts "Please log in"
end

puts "Access denied" unless logged_in
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Adding an else or complex conditions with and to unless, which becomes hard to read; use if instead.
  2. Using unless with a negation like unless !logged_in, creating a confusing double negative.
  3. Using elsif with unless, which is not allowed.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.