A queue is like a waiting list.
Imagine you’re waiting in line to buy the latest Apple product, getting a movie ticket, or to pay for your groceries.
These are queues!
You can use queues in your Ruby projects.
Queues allow you to process things in order of arrival, so they can be helpful for anything that requires things to be given priority the longer they have been waiting for.
You can apply this to:
- Model a real-world queue
- Implement algorithms like Breadth-First Search (BFS)
- Control access to a shared resource, like CPU, disks, printers, etc.
Let’s see some code!
How To Implement A Queue in Ruby
An array can behave like a
Queue if you use the right methods.
These methods are:
prependwith Ruby 2.5+)
unshift, you are adding one item to the queue.
queue =  queue.unshift "apple" queue.unshift "orange" queue.unshift "banana" # ["banana", "orange", "apple"]
pop, you remove the last item from the queue.
This is the next item that should be processed.
queue.pop # "apple" queue.pop # "orange"
You can look at the last item, to see “who’s next” without removing this item.
queue[-1] # "banana"
This operation is called
Ruby Concurrent Queue
Ruby has a proper thread-safe, blocking,
You can use this queue for coordinating work in a multi-threaded program.
que = Queue.new que << 1 que << 2 que << 3
You can get an item off this queue with
que.pop # 1 que.pop # 2
If the queue is empty, calling
pop will put your current thread to sleep & wait until something is added to the queue.
That’s what it means to “block”.
You can avoid blocking by passing
This will raise a
ThreadError: queue empty exception when the queue is empty.
How to Use A Sized Queue
A sized queue is the same as a regular queue but with a size limit.
que = SizedQueue.new(5)
When the queue is full, the
push (same as
<<) operation will suspend the current thread until an item is taken off the queue.
ThreadError: queue full.
You’ve learned about Ruby queues!
You can use a queue when you need to process work in FIFO (first-in-first-out) order. There are two ways to implement a queue, using an array, or using the
Thanks for reading. 🙂