We can delete an element from an array in several ways. However, the delete_at()
method provides us an additional option that allows us to delete an item at a specified index.
This means that we can specify the element we want to delete by just passing its index position to the delete_at()
method.
array.delete_at(index)
index
: The index position of the element that we want to delete.
The value returned is the element deleted.
Take a look at the code below to understand better this concept better. You can run the code to see the returned values.
# create several arraysarr1 = [1, 2, 3, 4, 5]arr2 = ["a", "b", "c", "d", "e"]arr3 = ["FireFox", "Chrome", ]arr4 = ["Google", "Netflix", "Apple", "Amazon"]# delete some elements# by using the delete_at() methoda = arr1.delete_at(2)b = arr2.delete_at(1)c = arr3.delete_at(0)d = arr4.delete_at(3)# print the returned valuesputs a # 3puts b # "b"puts c # "Firefox"puts d # "Amazon"
In the code above, we created some arrays and deleted some of their elements using the delete__at()
method. Then, we printed the returned values to the console.