How to Remove a Value at a Specific Index in a Ruby Array?

To remove a value at a specific index in a Ruby array, you can use the Array#delete_at method, which takes an index as an argument and removes the element at that index from the array, modifying the original array in place. For example:

arr = [1, 2, 3, 4, 5]
arr.delete_at(3)

print arr #=> [1, 2, 3, 5]

In the example above, specifying the index as 3, removes the fourth item in the array in place, resulting in [1, 2, 3, 5].

If the index is out of range, the Array#delete_at method returns nil. Otherwise, it returns the removed element. For example:

arr = [1, 2, 3, 4, 5]
deleted_item = arr.delete_at(5) # index out of range

print deleted_item #=> nil
print arr #=> [1, 2, 3, 4, 5]
arr = [1, 2, 3, 4, 5]
deleted_item = arr.delete_at(3) # index in range

print deleted_item #=> 4
print arr #=> [1, 2, 3, 5]

You can achieve the same using the Array#slice method as well, which works similar way to the Array#delete_at method for removing a value from an array at a specified index.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.