Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is array.delete() in Ruby?

okwudili onyejiaku

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:

Figure 1: element "a" deleted from array

Syntax

array.delete(element)
// where array is any Array instance

Parameters

element: The element or elements to delete.

Return value

  • 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.

Code

In the code below, several arrays are deleted with the delete() method and the returned values are printed to the console.

# create arrays
languagesArray = ["Java", "C++", "Python", "Javascript", "Ruby on Rails!" ]
numbersArray = [1, 2, 3, 4, 5]
alphabetsArray = ["a", "b", "c", "d", "e"]

# delete elements in arrays
a = languagesArray.delete("Java")
b = numbersArray.delete(3)
c = alphabetsArray.delete("b")

# print returned values
puts "Deleted elements are: \n"
puts a
puts b
puts c

# print orginal arrays
puts "Arrays after deletions are: \n"
puts "#{languagesArray}"
puts "#{numbersArray}"
puts "#{alphabetsArray}"

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring