What is array.unshift() in Ruby?

Overview

The array.unshift() method in Ruby is used to fill the array with elements that will begin at the front of the array.

It appends elements passed in as arguments to the front of the original array.

Syntax


array.unshift(element1, element2, ...elementN)

Parameter

element1, element2, .. element N: This is the element or elements you want to prepend to the array. It could be one element or more than one.

Return value

The value returned is an array with the elements passed as arguments prepended at the front of the array.

Code

In the example below, we will create arrays that are later prepended or filled at the front with elements or values passed as arguments.

# create arrays
arr1 = [1, 2, 3, 4, 5]
arr2 = ["a", "b", "c", "d", "e"]
arr3 = ["Ruby", "Java", "JavaScript", "Python"]
arr4 = ["1ab", "2cd", "3ef", "4gh", "5ij"]
arr5 = [nil, "nil", "true", "false", true]
# prepend arrays with elements with unshift()
a = arr1.unshift(6)
b = arr2.unshift("e", "f", "g")
c = arr3.unshift("C++", "Kotlin")
d = arr4.unshift("6kl", "7mn")
e = arr5.unshift(false)
# print modified array
puts "#{a}"
puts "#{b}"
puts "#{c}"
puts "#{d}"
puts "#{e}"

Explanation

From the code above, the elements passed as arguments are prepended to the arrays.


The unshift() method is one of the methods in Ruby that changes the original array.

Free Resources