liveBook · Manning

LIFO semantics

As explained in The Well-Grounded Rubyist, Fourth Edition

The LIFO principle specifies that the last item entering a collection is the first item leaving it.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines LIFO and demonstrates array-backed push and pop operations, without extending into broader stack algorithms.
Examples
Uses plates, printer paper, double-parked cars, and a Ruby Stacklike module as examples.
What you can do after
Apply it via Ruby modules by adding stacklike behavior to classes with array-backed push and pop methods.
How it connects
Connects stacks with modules, arrays, queues, and FIFO 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.