Let us say, we have a Array that contains three names, Mohan, Kriti and Salim. And we want to insert a new name Nikhil in between Mohan and Kriti.
We can achieve that using the insert() Method.
x = ["Mohan", "Kriti", "Salim"] x.insert(1,"Nikhil") puts x
So, in the above code we have created a Array and initialised to the variable x.
x = ["Mohan", "Kriti", "Salim"]
Below is how the values are positioned in the Array,
Now, if we see the above diagram, Kriti resides at position/index 1. So, what we do is, just insert the new name Nikhil at the position/index 1 using the insert() Method.
And Kriti gets shifted to index/position 2 and Salim to index 3. So, index 1 is available for the new element Nikhil.
x.insert(1,"Nikhil")
And the new array looks like,
['Mohan', 'Nikhil', 'Kriti', 'Salim']
Let us say, we have a Array that contains three names, Mohan, Kriti and Salim. And we want to insert a new name Sean at the beginning of the Array.
We can use the unshift() Method to achieve the above.
x = ["Mohan", "Kriti", "Salim"] x.unshift("Sean") puts x
So, in the above code we have created a Array and initialised to the variable x.
x = ["Mohan", "Kriti", "Salim"]
Below is how the values are positioned in the Array,
Next, we have used the unshift() Method to add the new name Sean at the beginning of the Array.
x.unshift("Sean")
And Sean gets added to the beginning of the Array.
And the new array looks like,
['Sean', 'Mohan', 'Kriti', 'Salim']
Let us say, we have a Array that contains three names, Mohan, Kriti and Salim. And we want to insert a new name Mika at the end of the Array.
We can use the push() Method or << to achieve the above.
Let us look at the push() Method first.
x = ["Mohan", "Kriti", "Salim"] x.push("Mika") puts x
So, in the above code we have created a Array and initialised to the variable x.
x = ["Mohan", "Kriti", "Salim"]
Below is how the values are positioned in the Array,
Next, we have used the push() Method to add the new name Mika at the end of the Array.
x.push("Mika")
And the new array looks like,
['Mohan', 'Kriti', 'Salim', 'Mika']
Let us look at the second way i.e. << to insert an element at the end of the array.
x = ["Mohan", "Kriti", "Salim"] x << ("Mika") puts x