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
