liveBook · Manning

Array#unshift

As explained in The Well-Grounded Rubyist, Fourth Edition

Array#unshift is a Ruby Array method that adds one or more objects to the beginning of an array.

Array#unshift adds one or more objects to the beginning of an array, shifting existing elements toward higher indexes. section 9.2.2

Add an element first

a = [1, 2, 3, 4] a.unshift(0) # a is now [0, 1, 2, 3, 4] section 9.2.2

Compare the methods used at array boundaries:

  • Use unshift to add at the beginning. section 9.2.2
  • Use push or << to add at the end; push accepts multiple arguments, while << adds one object. section 9.2.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines the operation and resulting array, but does not detail implementation internals or return behavior.
Examples
Uses a numeric array changed from [1,2,3,4] to [0,1,2,3,4].
What it assumes
Assumes familiarity with arrays, indexing, and calling methods with receiver-dot syntax.
What you can do after
Apply Array#unshift to place an object at the beginning of an existing array.
How it connects
Contrasts with push, <<, shift, and pop as corresponding methods for array-end insertion and removal.

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.