O'Reilly logo

A Common-Sense Guide to Data Structures and Algorithms by Jay Wengrow

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required