liveBook · Manning

Stacklikeness

As explained in The Well-Grounded Rubyist, Fourth Edition

Stacklikeness is the property of allowing items to be added at one end and removing the most recently added item first.

Stacklikeness means adding items at one end and removing the most recently added item first: last in, first out (LIFO). section 4.1.1

In Ruby, stacklike behavior belongs in a module when multiple kinds of objects may need the same operations. A module can then be mixed into classes that require that behavior. section 4.1.1

A Ruby stacklike module

The Stacklike module uses an array stored in @stack, exposing methods to add objects with push and remove the newest object with pop. 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 compact module definition and its stack, add, and remove operations. section 4.1.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains LIFO with physical analogies, then sketches Ruby module methods backed by an instance array.
Examples
Uses plates, printer paper, double-parked cars, cafeteria queues, and a Ruby Stacklike module.
What it assumes
Assumes familiarity with Ruby objects and classes while defining stacks and LIFO behavior through concrete examples.
What you can do after
Apply stacklike behavior to multiple Ruby classes by mixing in an array-backed module.
How it connects
Connects modules with classes, arrays, stacks, queues, and mixins.

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.