What Does Ruby's Array#shift do?

Ruby

Ruby Problem Overview


I am having a hard time understanding what the shift and unshift methods of the Array class do in Ruby. Can somebody help me understand what they do?

Ruby Solutions


Solution 1 - Ruby

Looking at the Ruby Documentation

Array.shift removes the first element from the array and returns it

a = [1,2,3] 
puts a.shift
 => 1 
puts a
 => [2, 3] 

Unshift prepends the provided value to the front of the array, moving all other elements up one

a=%w[b c d]
 => ["b", "c", "d"] 
a.unshift("a")
 => ["a", "b", "c", "d"] 

Solution 2 - Ruby

shift and unshift acts in similar way as pop and push: they are meant to use arrays as stacks to which you can append and remove elements (usually one per time). The difference is just that shift and unshift add/remove elements at the beginning of an Array, actually shifting all other elements, while pop and push add/remove elements at the end of the Array, so preserving other elements' indices.

Examples:

                      # Spacing for clarity:
a = [2, 4, 8]    # a =>       [2, 4, 8]
a.push(16, 32)   # a =>       [2, 4, 8, 16, 32]
a.unshift(0, 1)  # a => [0, 1, 2, 4, 8, 16, 32]
a.shift          # a =>    [1, 2, 4, 8, 16, 32]
a.pop            # a =>    [1, 2, 4, 8, 16]

Solution 3 - Ruby

It grabs the first element, removes it from the array, and returns the removed element. It's basically a way to treat an array like a stack: shift is pop, unshift is push.

Solution 4 - Ruby

If you can think of the array as being like a queue of values to be processed, then you can take the next (front) value and "shift" the other valuess over to occupy the space made available. unshift puts values back in - maybe you're not ready to process some of them, or will let some later code handle them.

Solution 5 - Ruby

It returns the first element of the array, and removes it from the array, shifting the elements back one place.

So shifting [1,2,3,4,5]

returns 1, and sets the array to be [2,3,4,5].

More here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionab217View Question on Stackoverflow
Solution 1 - RubySteve WeetView Answer on Stackoverflow
Solution 2 - RubyAlberto SantiniView Answer on Stackoverflow
Solution 3 - RubymipadiView Answer on Stackoverflow
Solution 4 - RubyTony DelroyView Answer on Stackoverflow
Solution 5 - RubyRob GrantView Answer on Stackoverflow