liveBook · Manning

Shift

As explained in The Well-Grounded Rubyist, Fourth Edition

Array#shift is a Ruby Array method that removes and returns the first element or a specified number of elements from an array.

Array#shift removes and returns the first element of an array. The array changes permanently, and the remaining elements move toward index zero. Passing an integer removes that many elements and returns them as an array. section 9.2.2

Removing from the beginning

a = [1, 2, 3, 4, 5] a.shift # => 1 a # => [2, 3, 4, 5] a.shift(2) # => [2, 3] a # => [4, 5] Use pop for the corresponding operation at the end of the array. section 9.2.2

Because shift mutates its argument, using it inside a method can consume the caller’s array. Repeated calls may therefore produce different results; Enumerable#reduce offers a side-effect-free alternative for summing elements. section 16.1.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines single- and multi-element removal, return shapes, mutation, and side-effect consequences, without pursuing implementation internals.
Examples
Uses irb examples that remove one or two values and a summation method that empties its input array.
What it assumes
Builds from array indexing and boundary operations, then teaches mutation through a deliberately destructive iteration example.
What you can do after
Apply it via Ruby to remove and capture leading array elements while recognizing when mutation can damage a caller’s data.
How it connects
Connects Array#pop, Array#unshift, Array#push, and Enumerable#reduce through boundary operations and mutation alternatives.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.