liveBook · Manning

Unless expression

As explained in The Well-Grounded Rubyist, Fourth Edition

The unless keyword introduces a conditional construct whose body executes when its condition is false.

The unless keyword runs its body when a condition is false, providing a natural alternative to if not or if !. section 6.1.1

A negative condition

unless x > 100 puts "Small number!" else puts "Big number!" end This is equivalent to testing x <= 100 with if. The unless/else form works, but if/else usually reads more clearly. section 6.1.1

Ruby also permits unless in modifier position, placing the condition after the statement; use it when the negative condition remains easy to follow. section 6.1.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains false-condition execution, equivalent negation, else behavior, and modifier placement, but not implementation internals.
Examples
Uses number-size classification and a minimal x == 1 condition to contrast unless with if.
What it assumes
Builds on if-style conditional tests and the idea of negating a condition.
What you can do after
Apply unless to write concise negative tests and choose if/else when an else branch improves clarity.
How it connects
Connects unless with if, else, negation, and modifier conditionals.

Also explained in

Compare how 2 books explain unless expression →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.