Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 134 ยท Control Flow

Ternary, Safe Navigation and Short-Circuit

Learn Ruby's compact conditionals - the ternary operator, safe navigation &., short-circuit && and ||, ||= and &&=, and idioms for handling nil without errors.

Ruby gives you several small operators for making decisions in a single expression: the ternary condition ? a : b, the safe navigation operator &., and the short-circuit operators && and || together with their assignment forms ||= and &&=. Used well, they remove whole if blocks. Used badly, they hide bugs. The most important job of this lesson is nil: the value that means "nothing here", and the cause of the most common Ruby error, NoMethodError: undefined method ... for nil.

You should already know what is truthy and falsy: only nil and false are falsy, and everything else, including 0, "" and [], is truthy. If that is new to you, read if, elsif, else and unless first.

The ternary operator

condition ? value_if_true : value_if_false is an if/else that returns a value.

Ruby Ternary basics

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 the ternary for a short choice between two simple values. Because Ruby's if is already an expression, the longer form on the last lines is equally valid and often easier to read once the branches grow.

Ternary pitfalls

  • Do not nest ternaries. a ? b : c ? d : e is legal but painful to read. Use if/elsif or case.
  • A symbol right after the question mark needs a space or parentheses. Ruby could read x ?a :b as a character literal.
  • Method names ending in ? are fine: list.empty? ? "none" : "some". Notice the space between the two question marks.
Ruby Predicate methods and ternaries

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.

Short-circuit && and ||

&& (and) returns the first falsy value, or the last value if all are truthy. || (or) returns the first truthy value, or the last value if all are falsy. They stop evaluating as soon as the result is known (that is "short-circuiting"), and they return actual values, not just true or false.

Ruby What && and || really return

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 "default value" pattern value || default is everywhere in Ruby. One trap: it replaces false as well as nil, so it is wrong when false is a legitimate value.

Ruby The false trap and fetch

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.

and, or and not versus &&, || and !

Ruby also has the low-precedence keywords and, or and not. They are meant for control flow, not for combining values, and they behave differently in assignments.

Ruby Why || and or are not the same

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 last line is the trap: = binds more tightly than or, so c is assigned nil. Use &&, || and ! for values and conditions. Keep and, or and not for rare control-flow lines like save or raise "failed"; many style guides forbid them entirely.

Safe navigation: &.

Calling a method on nil raises NoMethodError. The safe navigation operator &. calls the method only when the receiver is not nil. If the receiver is nil, the whole call returns nil and the arguments are not even evaluated.

Ruby NoMethodError on nil (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.

The hash has no :email key, so email is nil, and Ruby stops with main.rb:3:in '<main>': undefined method 'downcase' for nil (NoMethodError). Here is the fix:

Ruby Safe navigation in action

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.

Notice that &. guards only nil. It does not protect against false, or an object that lacks the method. A long chain such as a&.b&.c&.d is a code smell too: it means the caller knows too much about the shape of the data and often hides a design problem. Prefer returning an empty object, using dig, or a guard at the top of the method.

Hash dig and safe lookups

dig follows a path through nested hashes and arrays and returns nil if any step is missing.

Ruby dig for nested data

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.

||= and &&=

a ||= b means a || (a = b): assign only if a is currently falsy. It is the standard way to set defaults and to memoize (compute once, remember).

Ruby Defaults and memoization with ||=

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.

a &&= b assigns only if a is currently truthy, which is useful for transforming a value that might be nil.

Ruby &&= transforms only when present

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.

||= memoizes only truthy results. If the computation can legitimately return nil or false, it will rerun every time. In that case store a flag, or use defined?(@value) or a hash lookup with key?.

Handling nil: a short toolbox

There is more than one way to deal with a possibly missing value. Pick the one that matches your intent.

Ruby Five ways to deal with nil

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 to_s, to_a and to_h conversions are tidy because nil quietly becomes an empty string, array or hash. For strict code, raise early with fetch so a missing value is reported where it occurs, not three methods later.

When to use which

  • Ternary: one short choice between two simple values.
  • if/else or case: anything with more than two outcomes or long branches.
  • ||: defaults for values that cannot legitimately be false.
  • &.: an optional object that may truly be nil; do not chain it deeply.
  • ||=: defaults and memoization of truthy results.
  • fetch and dig: hash lookups where you decide what a missing key means.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does nil && puts("hi") return, and does it print anything?

    && returns the first falsy value and stops. The right side is never evaluated, so nothing is printed.
  2. 2. What does user&.name return when user is nil?

    Safe navigation skips the call and returns nil when the receiver is nil.
  3. 3. Why is flag = settings[:flag] || true risky?

    || treats false like nil, so a legitimate false is overwritten. Use fetch(:flag, true) instead.
  4. 4. After x = 5 and x ||= 10, what is x?

    ||= assigns only when the variable is falsy. Five is truthy, so it stays.
  5. 5. What is the value of c after c = nil or "x"?

    = binds tighter than or, so the line is (c = nil) or "x". Use || when you want the value.

Summary

  • cond ? a : b is a compact if/else expression. Avoid nesting it.
  • && and || short-circuit and return the deciding value, not just true or false.
  • value || default is the default-value idiom, but it also replaces false. Use fetch when false is valid.
  • &. returns nil instead of raising when the receiver is nil. Avoid long chains.
  • ||= assigns when the variable is falsy (defaults and memoization). &&= assigns when it is truthy.
  • Prefer &&, || and ! over and, or and not, which have very low precedence.

Next: Exceptions