0
0
RubyHow-ToBeginner · 3 min read

How to Remove Element from Array in Ruby: Simple Guide

In Ruby, you can remove an element from an array using delete to remove by value, or delete_at to remove by index. For conditional removal, use reject! or select! methods to filter elements.
📐

Syntax

Here are common ways to remove elements from an array in Ruby:

  • array.delete(value): Removes all elements equal to value.
  • array.delete_at(index): Removes element at the given index.
  • array.reject! { |item| condition }: Removes elements matching the condition.

Each method modifies the original array.

ruby
array.delete(value)
array.delete_at(index)
array.reject! { |item| condition }
💻

Example

This example shows how to remove elements by value, by index, and by condition.

ruby
fruits = ["apple", "banana", "cherry", "banana", "date"]

# Remove all "banana" elements
fruits.delete("banana")
puts fruits.inspect

# Remove element at index 1 ("cherry" after deletion)
fruits.delete_at(1)
puts fruits.inspect

# Remove elements that start with 'd'
fruits.reject! { |fruit| fruit.start_with?("d") }
puts fruits.inspect
Output
["apple", "cherry", "date"] ["apple", "date"] ["apple"]
⚠️

Common Pitfalls

One common mistake is confusing delete and delete_at. delete removes by value, while delete_at removes by index. Also, reject! returns nil if no elements are removed, which can cause unexpected results if not handled.

Another pitfall is modifying the array while iterating over it without using safe methods like reject!.

ruby
arr = [1, 2, 3, 4]

# Wrong: trying to delete by index with delete
arr.delete(2) # removes value 2, not element at index 2
puts arr.inspect

# Right: use delete_at to remove by index
arr.delete_at(2) # removes element at index 2
puts arr.inspect
Output
[1, 3, 4] [1, 3]
📊

Quick Reference

MethodDescriptionExample
delete(value)Removes all elements equal to valuearr.delete(3)
delete_at(index)Removes element at given indexarr.delete_at(0)
reject! { |item| condition }Removes elements matching conditionarr.reject! { |x| x.even? }

Key Takeaways

Use delete to remove elements by their value from an array.
Use delete_at to remove elements by their position (index).
Use reject! with a block to remove elements based on a condition.
Remember that delete_at expects an index, not a value.
reject! returns nil if no elements are removed, so check its return value if needed.