Exploring Stacks and Queues in Ruby

Introduction: Stacks and Queues

Welcome to an exploration of two foundational data structures: Stacks and Queues! These structures are essential for organizing data in a structured, efficient manner. Imagine a stack like a pile of plates, where the last plate added is the first to be removed (LIFO). In contrast, a queue is like a line at the store, where the first person in line is served first (FIFO). Let’s dive in and see how these structures work in Ruby!

Stacks: Last In, First Out (LIFO)

A stack follows the LIFO (Last In, First Out) principle. Think of a stack as a pile of plates — the last plate added is the first to be removed. In Ruby, arrays make a convenient base for stacks, using push to add items and pop to remove them.

Here’s a simple example using a stack of plates:

Ruby
class StackOfPlates
  def initialize
    @stack = []
  end

  # Add a plate to the top of the stack
  def add_plate(plate)
    @stack.push(plate)
  end

  # Remove the top plate from the stack
  def remove_plate
    return "No plates left to remove!" if @stack.empty?
    @stack.pop
  end
end

plates = StackOfPlates.new
plates.add_plate('Plate 1')
plates.add_plate('Plate 2')
puts "Removed: #{plates.remove_plate}"  # Output: Removed: Plate 2

In this example, the last plate added (Plate 2) is the first one removed, demonstrating the LIFO behavior of a stack.

Queues: First In, First Out (FIFO)

A queue follows the FIFO (First In, First Out) principle, much like waiting in line. Ruby arrays can also represent queues, where push adds an item to the end, and shift removes the item from the front.

Here’s an example of a queue of people:

class QueueOfPeople
  def initialize
    @queue = []
  end

  # Add a person to the end of the queue
  def enqueue_person(person)
    @queue.push(person)
  end

  # Remove the first person from the queue
  def dequeue_person
    return "No people left to dequeue!" if @queue.empty?
    @queue.shift
  end
end

people = QueueOfPeople.new
people.enqueue_person('Person 1')
people.enqueue_person('Person 2')
puts "Removed: #{people.dequeue_person}"  # Output: Removed: Person 1

Here, Person 1, the first to enter the queue, is also the first to leave, showcasing the FIFO behavior of a queue.

Stacks and Queues: When and Where to Use?

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal