Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
array
communitycreator

How to delete an element in an array using delete_at() in Ruby

okwudili onyejiaku

Overview

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.

Syntax

array.delete_at(index)

Parameters

index: The index position of the element that we want to delete.

Return value

The value returned is the element deleted.

Code example

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 arrays
arr1 = [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() method
a = arr1.delete_at(2)
b = arr2.delete_at(1)
c = arr3.delete_at(0)
d = arr4.delete_at(3)

# print the returned values
puts a      # 3
puts b      # "b"
puts c      # "Firefox"
puts d      # "Amazon"
Using the delete_at method

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.

RELATED TAGS

ruby
array
communitycreator
RELATED COURSES

View all Courses

Keep Exploring