What Does Ruby's Array#shift do?
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?
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"]
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]
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.