Class: DSA::Queue
- Inherits:
-
Object
- Object
- DSA::Queue
- Defined in:
- lib/dsa-ruby/queue.rb
Overview
DSA::Queue - First-In-First-Out (FIFO) data structure.
Instance Method Summary collapse
-
#dequeue ⇒ Object
Removes and returns the value at the front of the queue.
-
#empty? ⇒ Boolean
Checks if the queue is empty.
-
#enqueue(val) ⇒ DSA::Queue
Adds a value to the back of the queue.
-
#initialize ⇒ DSA::Queue
constructor
Initialize a new empty queue.
-
#peek ⇒ Object
Returns the value at the front of the queue without removing it.
-
#size ⇒ Integer
Returns the number of elements in the queue.
-
#to_a ⇒ Array
Returns a defensive copy of the queue as an array.
Constructor Details
#initialize ⇒ DSA::Queue
Initialize a new empty queue.
12 13 14 |
# File 'lib/dsa-ruby/queue.rb', line 12 def initialize @elements = [] end |
Instance Method Details
#dequeue ⇒ Object
Removes and returns the value at the front of the queue.
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.
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.
22 23 24 25 |
# File 'lib/dsa-ruby/queue.rb', line 22 def enqueue(val) @elements.push(val) self end |
#peek ⇒ Object
Returns the value at the front of the queue without removing it.
46 47 48 49 |
# File 'lib/dsa-ruby/queue.rb', line 46 def peek raise IndexError, "queue is empty" if empty? @elements.first end |
#size ⇒ Integer
Returns the number of elements in the queue.
57 58 59 |
# File 'lib/dsa-ruby/queue.rb', line 57 def size @elements.size end |
#to_a ⇒ Array
Returns a defensive copy of the queue as an array.
77 78 79 |
# File 'lib/dsa-ruby/queue.rb', line 77 def to_a @elements.dup end |