Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

unless

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.

The shortcut

Read unless aloud as "if not" and listen. If the sentence sounds natural ("print closed if not open"), keep unless. If it contains "not not", an else, or an and/or, rewrite it as an if.

Cleaning up a Bean Cart checkStep 1 of 4
  1. The original

    unless !sold_out followed by puts "Order taken".

Drills

Answer fast — trust the rule.

quick drill

When does the body of unless milk_ok run?

quick drill

Which is the same as puts "Closed" unless open?

quick drill

What does unless !sold_out really mean?

quick drill

What do Ruby style guides say about unless with else?

Remember

  • unless is if not; best as a short modifier guard.
  • Read it aloud as "if not": if you hear a double negative, an else or an and/or, switch to if.
  • Trap: unless with else, or a ! inside the unless condition.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainUntangle a double negative

Explain what puts "Order taken" unless !sold_out actually does, why it is hard to read, and rewrite it the way it was probably intended.