0
0
RubyHow-ToBeginner · 3 min read

How to Implement Queue in Ruby: Simple Guide and Example

In Ruby, you can implement a queue using an Array by adding elements with push and removing them with shift. For a more structured approach, create a Queue class with methods like enqueue and dequeue to manage the queue behavior.
📐

Syntax

A queue in Ruby can be implemented using an Array. Use push(element) to add items to the end and shift to remove items from the front, following the FIFO (First In, First Out) rule.

Alternatively, define a Queue class with methods:

  • enqueue(item): adds an item to the queue
  • dequeue: removes and returns the first item
  • peek: shows the first item without removing it
  • empty?: checks if the queue is empty
ruby
class Queue
  def initialize
    @items = []
  end

  def enqueue(item)
    @items.push(item)
  end

  def dequeue
    @items.shift
  end

  def peek
    @items.first
  end

  def empty?
    @items.empty?
  end
end
💻

Example

This example shows how to create a queue, add items, remove them, and check the queue's state.

ruby
class Queue
  def initialize
    @items = []
  end

  def enqueue(item)
    @items.push(item)
  end

  def dequeue
    @items.shift
  end

  def peek
    @items.first
  end

  def empty?
    @items.empty?
  end
end

queue = Queue.new
queue.enqueue("apple")
queue.enqueue("banana")
queue.enqueue("cherry")

puts queue.dequeue  # Output: apple
puts queue.peek     # Output: banana
puts queue.empty?   # Output: false
queue.dequeue
queue.dequeue
puts queue.empty?   # Output: true
Output
apple banana false true
⚠️

Common Pitfalls

One common mistake is using pop instead of shift to remove items, which breaks the FIFO order by removing from the end instead of the front.

Another pitfall is modifying the queue array directly from outside the class, which can cause unexpected behavior.

ruby
queue = []
queue.push(1)
queue.push(2)
queue.pop    # Removes 2, not 1 (wrong for queue)

# Correct way:
queue = []
queue.push(1)
queue.push(2)
queue.shift  # Removes 1 (correct FIFO)
📊

Quick Reference

OperationMethodDescription
Add itempush(item)Adds item to the end of the queue
Remove itemshiftRemoves item from the front of the queue
Check first itemfirst or peek methodReturns the first item without removing
Check emptyempty?Returns true if queue has no items

Key Takeaways

Use an array with push and shift to implement a queue in Ruby.
Create a Queue class for clearer, reusable queue operations.
Always remove items with shift to maintain FIFO order.
Avoid directly modifying the queue's internal array from outside.
Use methods like peek and empty? to safely inspect the queue.