Ruby delete array method

In ruby programming language, delete() method are used to remove all particular object from array. And this method is returns the last deleted element. Syntax of this method as follows.

Syntax Array.delete(object)
Parameter Deleted object in array
Return Last deleted objects, or nil

When deleted objects are not found in array this method is return a nil value.

Ruby delete method example

This method are removing whose element which value is similar to given object. lets seen an example.

# Example 1

# Our array
record = [1,4,2,3,4,4]

# Before delete
print(" Before delete : ")
print("\n record : ", record)

# Deleted element 4
v = record.delete(4)

# After delete
print("\n After delete : ")
print("\n record : ", record)
print("\n v : ", v)
Ruby delete method example 1
 Before delete : 
 record : [1, 4, 2, 3, 4, 4]
 After delete : 
 record : [1, 2, 3]
 v : 4

In the above example, the element is removed, the value of which is 4. When remove element are not exists in this case it return nil and not modifies the actual array.

When there are no removed elements, we can provide to the alternate value by this method. For this used block statement after the method.

# Example 2

# Our array
record = [1,2,3,6]

# Before delete
print(" Before delete : ")
print("\n record : ", record)

# Deleted element 5
v = record.delete(5){"Missing"}

# After delete
print("\n After delete : ")
print("\n record : ", record)
print("\n v : ", v)
Ruby delete method example 2
 Before delete : 
 record : [1, 2, 3, 6]
 After delete : 
 record : [1, 2, 3, 6]
 v : Missing


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved