What are Queues in ROR?
Queues are just like a waiting list. Imagine a scenario where you have to withdraw cash from the bank and you stand in a line waiting for your turn – this is a real-life example of a queue.
In Ruby, the implementation of Queue is similar to other object-oriented languages such as Java or Python.
Implementation
Ruby on Rails has a built-in class Queue that implements multi-producer, multi-consumer queues.
Some built-in methods in Ruby Queue Class include:
push() and pop()in Queue
-
push()- inserts the element in the queue -
pop()- returns the element in the front of the queue and removes it from the queue
q1 = Queue.new
q1.push(5)
q1.push(6)
puts q1.pop()
shift() in Queue
- returns and removes the front element of the queue
q1 = Queue.new
q1.push(5)
q1.push(6)
puts q1.shift()
close() in Queue
- closes the queue permanently and does not allow any more push or pop operations
A closed queue cannot be re-opened.
q1 = Queue.new
q1.push(5)
q1.push(6)
q1.close() //closes the queue
puts q1.close() //checks whether the queue is closed or not.
clear() in Queue
- clears the queue and returns its size to zero
We can also re-insert objects into the queue.
q1 = Queue.new
q1.push(5)
q1.push(6)
q1.clear()
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved