August 2017
Intermediate to advanced
222 pages
5h 3m
English
Queues are common in many applications, ranging from printing jobs to background workers in web applications.
Let’s say you were programming a simple Ruby interface for a printer that can accept printing jobs from various computers across a network. By utilizing the Ruby array’s push method, which adds data to the end of the array, and the shift method, which removes data from the beginning of the array, you may create a class like this:
| | class PrintManager |
| | |
| | def initialize |
| | @queue = [] |
| | end |
| | |
| | def queue_print_job(document) |
| | @queue.push(document) |
| | end |
| | |
| | def run |
| | while @queue.any? |
| | # the Ruby shift method removes and returns the |
| | # first element of an array: |
| | print(@queue.shift) |
| | ... |