In Ruby, to add items to the start of an array, we can simply use the Ruby unshift method. The unshift method will add an element to the start of the array.

num_array = [1, 2, 3]
num_array.unshift(4);

print num_array

#Output:
[4, 1, 2, 3]

We can also use the unshift method to add multiple elements to an array.

num_array = [1, 2, 3]
num_array.unshift(4,5);

print num_array

#Output:
[4, 5, 1, 2, 3]

When working with collections of data in Ruby, the ability to easily add items or change the collection is important. One such case where we may want to modify a collection is if we want to add elements to an array in Ruby. To add an item to an array in Ruby, we can use the unshift method. The unshift method will add an element or elements to the start of the array.

Below shows a simple example of how we can use the unshift method to add an item to the start of an array in Ruby.

string_array = ["red","yellow","black","blue"];
string_array.unshift("orange")

print string_array

#Output:
["orange", "red", "yellow", "black", "blue"]

Adding Multiple Items to the Start of an Array in Ruby

If we want to add multiple items to an array in Ruby, then we could once again use the unshift method and include multiple items in it. Below is the code to add multiple elements to an array using the unshift method in Ruby.

colors_array = ["red","yellow","black","blue"];
colors_array.unshift("orange","pink","purple")

print colors_array

#Output:
["orange", "pink", "purple", "red", "yellow", "black", "blue"]

Using the prepend Method to Add Items to the Start of an Array in Ruby

Another method we can use to add items to the start of an array is the Ruby prepend method. The prepend method works in the same way as the unshift method, and we can add one or multiple items to an array using it. Let’s see an example of this method.

colors_array = ["red","yellow","black","blue"];
colors_array.prepend("orange")

print colors_array

#Output:
["orange", "red", "yellow", "black", "blue"]

And here is an example of adding multiple items to the start of an array using the prepend method in Ruby.

colors_array = ["red","yellow","black","blue"];
colors_array.prepend("orange","pink","purple")

print colors_array

#Output:
["orange", "pink", "purple", "red", "yellow", "black", "blue"]

Hopefully this article has been useful for you to learn how to use the Ruby unshift method.

Categorized in:

Ruby,

Last Update: March 1, 2024