Lesson Overview

Welcome to our exploration of queues and deques in Ruby. These data structures are fundamental in programming, managing tasks in applications, from job scheduling to executing sequences of operations. In this lesson, our aim is to understand and implement queues and deques using Ruby's versatile array features. Let's dive in!

Introduction to Queues

A queue operates on the "First In, First Out," or FIFO, principle, much like waiting your turn at a coffee shop. In Ruby, we can utilize arrays to implement queue functionality. The push method allows us to enqueue items, while shift can dequeue them.

# Create a queue and add items
queue = []
queue.push("Apple")
queue.push("Banana")
queue.push("Cherry")

# Remove an item
puts queue.shift  # Expects "Apple"

The item "Apple" is removed first, illustrating the FIFO nature of queues.

Practical Implementation of Queues

Before removing items from a queue, we should verify that the queue is not empty. This check is crucial to avoid runtime errors during the dequeue process.

# Create a queue and enqueue items
queue = []
queue.push("Item 1")
queue.push("Item 2")

# Check if the queue is non-empty, then dequeue an item
if !queue.empty?
  puts queue.shift  # Expects "Item 1"
end
Introduction to Deques

A deque, or "double-ended queue," permits adding and removing items from both ends. Ruby's arrays can manage deques via operations like push, unshift (to add items to the left), pop (to remove from the right), and shift (to remove from the left).

# Create a deque and add items
deque = []
deque.push("Middle")
deque.push("Right end")
deque.unshift("Left end")

# Remove an item from the right
puts deque.pop  # Expects "Right end"

# Remove an item from the left
puts deque.shift  # Expects "Left end"
Deques Rotations

Ruby arrays have a convenient rotate method, allowing us to cyclically shift elements by a specified number, enhancing deque operations.

# Create a deque
deque = ["Apple", "Banana", "Cherry"]

# Rotate the deque
deque.rotate!(1)  # Rotates to the left by one place

puts deque.inspect  # Expects ["Banana", "Cherry", "Apple"]

Here, rotate!(1) shifts all elements one position to the left.

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