Reputation: 17160
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?
Upvotes: 95
Views: 59634
Reputation: 6562
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]
Upvotes: 60
Reputation: 7348
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.
Upvotes: 1
Reputation: 410672
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.
Upvotes: 9
Reputation: 106106
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.
Upvotes: 2
Reputation: 28392
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"]
Upvotes: 106