unless and Modifier Conditions
Prerequisites: Conditionals
Ruby has two extra ways to write conditions that make simple checks read more naturally.
unless
unless is the opposite of if: the code runs when the condition is
false.
logged_in = false
unless logged_in
puts "Please log in"
end
Please log in
That reads better than if !logged_in. Avoid unless with else or
with complicated conditions — double negatives are hard to read.
Modifier form
When the body is a single line, you can put the condition after it:
stock = 0
puts "Out of stock!" if stock.zero?
puts "Order more" unless stock > 5
Out of stock!
Order more
This is extremely common in Ruby code — especially for guard clauses, which exit a method early when something is wrong (you'll see these in the Methods lessons):
return if name.empty?
Common mistakes
- Using the modifier form for long lines. If the statement doesn't fit
comfortably on one line, use a normal
if ... endblock.
Practice
Rewrite this using a modifier unless:
if !password.empty?
puts "Password set"
end
Show solution
password = "secret"
puts "Password set" unless password.empty?