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

unless

In this page:

  1. unless

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
🔒

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.