Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 134 ยท Control Flow

if, elsif, else and unless

Learn Ruby conditionals - if, elsif, else, unless, modifier forms, conditionals as expressions, truthiness (only nil and false are falsy), guard clauses and common pitfalls.

Programs make decisions. In Ruby the main decision tools are if, elsif, else and unless. They look familiar if you have used another language, but Ruby adds two twists that change how you write code: conditionals are expressions (they produce a value), and they can be written after the statement they guard. Combined with Ruby's simple truthiness rule, this lets you write short, readable code.

This lesson covers each form, the truthiness rule, one-line and modifier styles, guard clauses, and the mistakes that trip people up. Multi-way branching on a single value continues in case and when, and structural matching in Pattern Matching.

The basic if

Ruby if, elsif and else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

There are no parentheses around the condition and no braces around the body: the block ends with end. Note the spelling elsif (not elseif, else if or elif). Writing else if starts a new nested if that needs its own end, which is a common source of "unexpected end-of-input" syntax errors.

Ruby runs the first branch whose condition is truthy and skips the rest. The then keyword is optional on separate lines but required (or a semicolon) for single-line forms.

Truthiness: only nil and false are false

This rule is simpler than in most languages. Every value is truthy except false and nil.

Ruby What counts as true

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Surprises for people coming from JavaScript, Python or C: 0, "", [], {} and 0.0 are all truthy. To test for emptiness, ask explicitly with empty?, zero? or nil?:

Ruby Test what you mean

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Methods that end with ? return a boolean and are designed for conditions. if nickname is the natural idiom for "if a value is present", and it handles both nil and false at once.

Conditionals are expressions

In Ruby, if returns the value of the branch that ran (or nil if no branch ran). So you can assign the result directly:

Ruby if as an expression

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Because the last expression is a method's return value (see Methods), a method can be just an if with no return at all. Be careful when a branch that doesn't run leaves you with nil that you did not expect: add an else when a value is required.

The ternary operator

For a simple two-way choice, condition ? a : b is compact:

Ruby Ternary choice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Keep ternaries to one short condition. If you need a second ?, switch to if/elsif or a case. The ternary operator has its own lesson with safe navigation idioms: Ternary, Safe Navigation and Short-Circuit.

Modifier form: if and unless after a statement

When the body is one short statement, put the condition after it. This is idiomatic Ruby and reads like English.

Ruby Modifier if and unless

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The modifier form is for simple cases. If the line gets long or the condition complicated, use the block form. Never stack several modifiers on a line (do_a if x unless y), which is hard to read.

Guard clauses

The return ... if lines in check are guard clauses: they handle the unusual cases first and exit early, so the main logic sits at the left margin without deep nesting. Compare:

Ruby Nested if versus guard clauses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Both give the same answers; the second is easier to read and to extend.

unless

unless is "if not". It runs its body when the condition is falsy.

Ruby unless

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Use unless for simple negative conditions with no else. Avoid unless with else (read the branches in your head: "unless X, do A, otherwise B" is harder than "if X, do B, otherwise A"), and avoid unless combined with &&, || or and, because double negatives like unless a && !b are puzzles. There is no elsunless. When in doubt, use if with !.

Combining conditions

Ruby and, or, not in conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Use &&, || and ! in conditions. The English-word versions have different precedence (Operators). When you compare one value to many candidates, include? on an array or a case statement beats a chain of == and ||.

Assignment in a condition

Because = returns the assigned value, you can capture a value and test it in one step:

Ruby Assign and test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The extra parentheses are a convention that says "yes, I meant assignment, not ==". A bare if x = 5 prints main.rb:2: warning: found '= literal' in conditional, should be == (when it is on line 2), which is almost always a typo.

Pitfalls

Forgetting that zero is truthy

Ruby Zero is truthy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

In languages where 0 is falsy this check would wrongly say "not found" for an index of 0. In Ruby if index is correct.

else if instead of elsif

Ruby else if opens a new if (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

This program is missing an end because else if opens a second if. Ruby reports main.rb:8: syntax errors found (SyntaxError), with the notes "expected an end to close the else clause" and "unexpected end-of-input". Write elsif and the problem disappears.

Comparing with = and ==

= assigns, == compares. Ruby warns about the typo only when the right side is a literal, so keep your eyes open.

Using and/or where &&/|| are meant

if a and b works, but x = a and b does not do what you think (see Operators). Prefer symbols in conditions.

When to use what

Situation Use
Two or three branches on different conditions if / elsif / else
One short action, simple condition modifier if / unless
Choose between two values ternary ? : (one level only)
Same value compared to many options case/when (case and when)
Checking the shape of data pattern matching (Pattern Matching)
Early exit on bad input guard clause with return

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which values are falsy in Ruby?

    Ruby treats everything except nil and false as truthy, including zero, empty strings and empty arrays.
  2. 2. What is printed by x = if false then 1 end; p x?

    An if with no matching branch evaluates to nil, and that nil is assigned to x.
  3. 3. Which keyword is correct for an additional condition after if?

    Ruby spells it elsif. Writing else if opens a nested if that needs its own end.
  4. 4. What does puts "low" if balance < 100 do when balance is 150?

    The modifier if runs the statement only when the condition is truthy, so nothing is printed.
  5. 5. What is a guard clause?

    Guard clauses such as return "no order" unless order handle edge cases first so the main logic is not nested.

Summary

  • if, elsif, else and end branch on conditions; the keyword is elsif.
  • Only nil and false are falsy; 0, "" and [] are truthy.
  • Conditionals are expressions: assign them, or let them be a method's last value; with no matching branch the result is nil.
  • Use modifier if/unless for one-line actions and guard clauses for early exits.
  • Use unless for simple negations without else; the ternary only for short, single-level choices.
  • Wrap deliberate assignments in conditions in parentheses.

Next: case and when