liveBook · Manning

Else clause

As explained in The Well-Grounded Rubyist, Fourth Edition

The else keyword introduces the alternative branch of a conditional statement when preceding conditions do not succeed.

An else clause supplies the fallback branch of an if statement. Ruby executes it only when the if condition and every preceding elsif condition fail. section 6.1.1

if condition
  # code executed if condition is true
else
  # code executed if condition is false
end

Use else to separate the code for a true condition from the code for every false case. section 6.1.1

Branch selection follows a fixed order:

  • Ruby executes the first successful if or elsif branch and ignores the remaining branches. section 6.1.1
  • Ruby executes else when none of the preceding tests evaluates as true. section 6.1.1
  • Ruby returns nil when all conditions fail and no else clause exists. section 6.1.1

Classifying a number

An if/elsif/else chain prints whether an entered integer is positive, negative, or zero; else handles the remaining case.

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains branch ordering, elsif cascading, and nil when no fallback exists.
Examples
Uses number classification to distinguish positive, negative, and zero values.
What it assumes
Assumes familiarity with if conditions and introduces fallback behavior alongside elsif chains.
What you can do after
Apply it in Ruby to provide a definite fallback branch for conditional logic.
How it connects
Connects conditional statements with if clauses, elsif clauses, truth evaluation, and nil.

Also explained in

Compare how 5 books explain else clause →

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.