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
