Home »
Ruby Tutorial
Ruby Array.unshift() Method
By IncludeHelp Last updated : December 01, 2024
In this article, we will study about Array.unshift() Method. You all must be thinking the method must be doing something which is related to unshifting of objects in the Array instance. It is not as simple as it looks. Well, we will figure this out in the rest of our content. We will try to understand it with the help of syntax and demonstrating program codes.
Description and Usage
This method is a public instance method and defined for the Array class in Ruby's library. This method works in a way that affixes the object which is provided with the method at the time of its invocation to the front of the self Array object. It simply means that the object will be shifted to the 0th index and the indices of rest objects are incremented by one. You can provide more than one argument to the method at the time of its invocation. This method is one of the examples of destructive methods where the changes created by the method are permanent. There is no non-destructive version of this method.
Syntax
array_instance.unshift(object) -> array
Parameters
This method can take n number of objects. You can even provide an Array instance as the argument.
Example 1
=begin
Ruby program to demonstrate unshift method
=end
# array declaration
table = [2,4,8,10,12,134,160,180,200,344]
puts "Array unshift implementation"
puts "Enter the number of objects you want to add:"
num = gets.chomp.to_i
for i in 1..num
puts "Enter the object:"
ele = gets.chomp
table.unshift(ele)
end
puts "The final Array instance: #{table}"
Output
Array unshift implementation
Enter the number of objects you want to add:
3
Enter the object:
Hrithik
Enter the object:
Amisha
Enter the object:
Satyam
The final Array instance: ["Satyam", "Amisha", "Hrithik", 2, 4, 8, 10, 12, 134, 160, 180, 200, 344]
Explanation
In the above code, you can observe that we are adding elements in the Array instance with the help of the Array.unshift() method. In the output, you can see that the objects which are given by the user are stored from 0th index. The previously present elements are moved upward.
Example 2
=begin
Ruby program to demonstrate unshift method
=end
# array declaration
table = [2,4,8,10,12,134,160,180,200,344]
puts "Array unshift implementation"
Name = ["Ayush","Saksham","Nikhil"]
table.unshift(Name)
puts "The final Array instance: #{table}"
Output
Array unshift implementation
The final Array instance: [["Ayush", "Saksham", "Nikhil"], 2, 4, 8, 10, 12, 134, 160, 180, 200, 344]
Explanation
In the above code, you can observe that we have prepended an Array instance in the self Array. Now, it has become a subarray of the self Array which is stored at the 0th index of the self Array.