Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 30 / 68

Stacks and Queues (Basic Data Structures)

In this lesson you will learn the difference between a stack and a queue, and how to build each one in Ruby. This is for anyone searching for "Ruby stack queue implementation".

A stack is "last in, first out" and a queue is "first in, first out". The difference between a pile of books and a queue of people is a helpful picture.

The sample code builds a stack by adding to the end with .push and taking from the end with .pop, and a queue by adding to the end with .push and taking from the front with .shift. Notice how the same array behaves as a completely different structure just by changing where you take items from.

A common stumbling block for beginners is the difference between .pop and .shift. Both remove one element, but pop takes it from the end and shift from the front. Miss that and the items come out in the wrong order.

Which structure you pick changes the order of processing and the efficiency of your algorithm considerably. Picturing a pile of books against a queue of people makes the difference easy to keep straight.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)