The delete()
method of the Array
class in Ruby deletes a specified element from an Array
instance.
The figure below illustrates how the delete()
method works:
array.delete(element)
// where array is any Array instance
element
: The element or elements to delete.
The delete()
method returns the deleted item or the last deleted item if there is more than one item to delete.
If no matching item is found, then it returns nil
.
In the code below, several arrays are deleted with the delete()
method and the returned values are printed to the console.
# create arrayslanguagesArray = ["Java", "C++", "Python", "Javascript", "Ruby on Rails!" ]numbersArray = [1, 2, 3, 4, 5]alphabetsArray = ["a", "b", "c", "d", "e"]# delete elements in arraysa = languagesArray.delete("Java")b = numbersArray.delete(3)c = alphabetsArray.delete("b")# print returned valuesputs "Deleted elements are: \n"puts aputs bputs c# print orginal arraysputs "Arrays after deletions are: \n"puts "#{languagesArray}"puts "#{numbersArray}"puts "#{alphabetsArray}"