Skip to the workspace
Pebellslearn by building
Conditional Statements  ›  Lesson

unless

unless 12 minunless runs its body when the condition is falsy, exactly like if not, and reads best as a short modifier without an else or extra negation.

ruby / unless

Explore each scene at your own pace.

01 · The rule

The rule

unless

unless runs its body when the condition is falsy, exactly like if not, and reads best as a short modifier without an else or extra negation.

Express a negative condition without hiding a more complex decision.

Bean Cart should warn the barista when the milk runs low. You could write if !milk_ok, but that little ! is easy to miss when you skim. Ruby has a keyword that reads the way you would say it out loud: "warn, unless the milk is fine".

The rule

unless is if not; keep it short and never give it an else.

unless runs its body when the condition is falsy:

unless milk_ok
  puts "Order more milk!"
end

That is exactly the same as:

if !milk_ok
  puts "Order more milk!"
end

Its best use is the modifier form, often as a guard at the start of some code:

puts "Cart is closed" unless open
puts "Out of oat milk" unless stock[:oat_milk] > 0

Like if, unless is an expression and returns the value of the body, or nil when the body does not run.

Ruby allows unless ... else ... end, but the result is a double negative that readers must untangle:

# Hard to read: "unless not open... wait"
unless open
  puts "Closed"
else
  puts "Welcome"
end

# Clear: flip it to an if
if open
  puts "Welcome"
else
  puts "Closed"
end

Style guides, and tools such as RuboCop, recommend never pairing unless with else. There is also no elsunless.

Avoid negative conditions inside unless as well. unless !sold_out means "if sold out", so write that. The same goes for compound conditions: unless a && b makes readers apply De Morgan's laws in their heads.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.