Elements in Arrays
Learn how to add, select, and reject elements in an array in the Ruby language.
Adding elements to arrays
Adding and removing elements are implemented with methods we already know: push
and pop
. These methods perform operations with the tail of an array, meaning they add an element to the end, and remove it from the end. It looks like a stack of plates, where we can push
and pop
from the top.
However, there are unshift
and shift
methods that do the same, but with the head of an array:
unshift
is similar topush
shift
is similar topop
The metaphor here could be that the shift
shifts elements and returns the one that doesn’t fit.
Get hands-on with 1400+ tech skills courses.