Queues in Action

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​)
  ​ ...

Get A Common-Sense Guide to Data Structures and Algorithms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.