Class: DSA::Queue

Inherits:
Object
  • Object
show all
Defined in:
lib/dsa-ruby/queue.rb

Overview

DSA::Queue - First-In-First-Out (FIFO) data structure.

Examples:

queue = DSA::Queue.new
queue.enqueue("a").enqueue("b").enqueue("c")
queue.dequeue  # => "a"
queue.peek     # => "b"

Instance Method Summary collapse

Constructor Details

#initializeDSA::Queue

Initialize a new empty queue.



12
13
14
# File 'lib/dsa-ruby/queue.rb', line 12

def initialize
  @elements = []
end

Instance Method Details

#dequeueObject

Removes and returns the value at the front of the queue.

Examples:

queue.enqueue("a").enqueue("b")
queue.dequeue  # => "a"

Returns:

  • (Object)

    the value at the front of the queue

Raises:

  • (IndexError)

    if the queue is empty



34
35
36
37
# File 'lib/dsa-ruby/queue.rb', line 34

def dequeue
  raise IndexError, "queue is empty" if empty?
  @elements.shift
end

#empty?Boolean

Checks if the queue is empty.

Examples:

queue = DSA::Queue.new
queue.empty?  # => true

Returns:

  • (Boolean)

    true if the queue contains no elements



67
68
69
# File 'lib/dsa-ruby/queue.rb', line 67

def empty?
  @elements.empty?
end

#enqueue(val) ⇒ DSA::Queue

Adds a value to the back of the queue.

Examples:

Enqueue with chaining

queue.enqueue("a").enqueue("b").enqueue("c")

Parameters:

  • val (Object)

    the value to add to the queue

Returns:



22
23
24
25
# File 'lib/dsa-ruby/queue.rb', line 22

def enqueue(val)
  @elements.push(val)
  self
end

#peekObject

Returns the value at the front of the queue without removing it.

Examples:

queue.enqueue("a").enqueue("b")
queue.peek  # => "a"

Returns:

  • (Object)

    the value at the front of the queue

Raises:

  • (IndexError)

    if the queue is empty



46
47
48
49
# File 'lib/dsa-ruby/queue.rb', line 46

def peek
  raise IndexError, "queue is empty" if empty?
  @elements.first
end

#sizeInteger

Returns the number of elements in the queue.

Examples:

queue.enqueue("a").enqueue("b")
queue.size  # => 2

Returns:

  • (Integer)

    the number of elements



57
58
59
# File 'lib/dsa-ruby/queue.rb', line 57

def size
  @elements.size
end

#to_aArray

Returns a defensive copy of the queue as an array.

Examples:

queue.enqueue("a").enqueue("b").enqueue("c")
queue.to_a  # => ["a", "b", "c"]

Returns:

  • (Array)

    an array containing all elements in queue order (front to back)



77
78
79
# File 'lib/dsa-ruby/queue.rb', line 77

def to_a
  @elements.dup
end