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.
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 Queuepush()
- 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 Queueq1 = Queue.new
q1.push(5)
q1.push(6)
puts q1.shift()
close()
in QueueA 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 QueueWe can also re-insert objects into the queue.
q1 = Queue.new
q1.push(5)
q1.push(6)
q1.clear()
Free Resources