liveBook · Manning

Or-equals operator

As explained in The Well-Grounded Rubyist, Fourth Edition

The or-equals operator assigns its right-hand value only when its left-hand variable is nil or false.

The or-equals operator (||=) assigns the right-hand value only when the left-hand variable is nil or false. It is useful for giving an object a default value the first time it is needed. section 4.1.1

Lazy stack initialization

In the Stacklike module, @stack ||= [] creates an empty array when @stack has not been initialized. Later calls reuse the existing array, allowing stack, add_to_stack, and take_from_stack to share the same stored collection. 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

Inspect the complete Stacklike module to see ||= placed inside the stack accessor and supporting push and pop operations. section 4.1.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains the operator through a runnable module example, without developing broader edge cases or implementation internals.
Examples
Demonstrates @stack ||= [] as the backing initialization for a LIFO Stacklike module.
What you can do after
Apply it to lazily initialize an instance variable while preserving an already assigned value.
How it connects
Connects conditional assignment with modules, instance variables, arrays, and stack behavior.

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.