LIFO means “last in, first out”: the most recently added item leaves first. A stack of plates illustrates the rule, as do printer paper and double-parked cars. section 4.1.1
Stacklike behavior can be shared across different classes through a module. An array stores the items, while pushing adds to the stack and popping removes the newest item. section 4.1.1
A stack of plates
Place plates on a stack in the order A, B, then C. Removing plates returns C first, followed by B and A. 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
See the Stacklike module’s push-and-pop methods and its array-backed storage. section 4.1.1
