liveBook · Manning

Shortcut operator

As explained in The Well-Grounded Rubyist, Fourth Edition

A shortcut operator is Ruby syntax that combines an operation with assignment and expands to a call to an underlying method.

A shortcut operator combines an operation with assignment. For example, `a += 1` expands to `a = a + 1`, which is also `a = a.+(1)`: a call to the underlying method. section 4.1.1

Lazy initialization with ||=

A stack can initialize its storage only when needed: `@stack ||= []`. The first call assigns an empty array when `@stack` is `nil` or `false`; later calls return the existing array. Unlike operators such as `+=`, `||=` performs conditional assignment rather than simply wrapping an underlying method call. section 4.1.1

Ruby provides shortcut forms for several operations:

  • `-=`, `*=`, `/=`, `**=`, `&=`, `|=`, `^=`, and `%=` expand through their corresponding methods; `&&=` behaves similarly to `||=`. section 4.1.1
  • Any object with the relevant method can use the matching shortcut, including instances of custom classes that define methods such as `+`. section 4.1.1
Listing 4.1 Stacklike module, encapsulating stacklike structure and behavior
module Stacklike
  def stack
    @stack ||= []         1
  end
  def add_to_stack(obj)       2
    stack.push(obj)
  end
  def take_from_stack       3
    stack.pop
  ends
end

The Stacklike module demonstrates `||=` in a runnable initialization pattern, alongside methods that push objects onto and pop objects from the stored array. section 4.1.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains expansions to underlying method calls and contrasts them with conditional `||=` behavior, while deferring fuller treatment.
Examples
Uses `@stack ||= []`, `a += 1`, and a Stacklike module with push and pop operations.
What it assumes
Assumes familiarity with Ruby variables, instance variables, methods, arrays, and assignment while demonstrating initialization from zero.
What you can do after
Apply Ruby shortcut operators and recognize the underlying method calls or conditional assignments they represent.
How it connects
Connects shortcut operators with assignment, methods, objects, custom classes, instance variables, and modules.

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.