Ruby delete_at array method

In ruby programmer language, delete_at(index) array method are used to remove element of specified index. This method are accepting an parameter value that indicates the position of the element to be removed.

Syntax Array.delete_at(index)
Parameter Location of deleted element
Return nil, or deleted element

This parameter value status represents the array index. When delete index are invalid this method are not delete any element and return nil value.

Ruby delete_at method example

In this section mention few examples to deleted_at() method which is describe its functionality.

# Example 1

# Our array
record = [10,true,[1,2], 20]

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

# delete index 2
v = record.delete_at(2)

# Display array
print("\n After delete ");
print("\n record : ", record)

# Display delete element
print("\n v : ", v)
Ruby delete_at method example 1
 Before delete 
 record : [10, true, [1, 2], 20]
 After delete 
 record : [10, true, 20]
 v : [1, 2]

In the above example, the second element is removed. After that next element index are modified (reducing by one). And this method are return the delete element. The parameters of this method can be positive and negative values.

# Example 2

# Our array
record = [11,12,30,true,7, 20]

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

# delete index 2
v1 = record.delete_at(2)
# delete second last
v2 = record.delete_at(-2)

# Display array
print("\n After delete ");
print("\n record : ", record)

# Display delete element
print("\n v1 : ", v1)
print("\n v2 : ", v2)
Ruby delete_at method example 2
 Before delete 
 record : [11, 12, 30, true, 7, 20]
 After delete 
 record : [11, 12, true, 20]
 v1 : 30
 v2 : 7

When provide the positive integer value then index start with [0..n]. When parameter is negative then [-1] indicate last element and [-2] indicate second last element of array.



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