Remove an Array Element in Ruby

Nurudeen Ibrahim Feb 07, 2022
  1. Remove an Array Element Using the reject Method
  2. Remove an Array Element Using the Array Subtraction
  3. Remove an Array Element Using the delete Method
  4. Remove an Array Element Using the delete_if Method
Remove an Array Element in Ruby

Listed below are different ways of removing an element from an array in Ruby.

Remove an Array Element Using the reject Method

This method iterates through the array and returns only the elements that do not match a specified condition.

numbers = [2, 4, 6, 8, 10]
numbers_without_six = numbers.reject { |n| n == 6 }
puts numbers_without_six

Output:

[2, 4, 8, 10]

Remove an Array Element Using the Array Subtraction

An array can be subtracted from another array using the minus - operator in Ruby. For example, given that A and B are arrays, A - B takes out all elements of B found in A and returns the remaining elements of A.

We can rewrite the above example as done below to use this method.

numbers = [2, 4, 6, 8, 10]
numbers_without_six = numbers - [6]
puts numbers_without_six

Output:

[2, 4, 8, 10]

Remove an Array Element Using the delete Method

This deletes an array element, modifies the original array, and returns the deleted value.

numbers = [2, 4, 6, 8, 10]
numbers.delete(6)
puts numbers

Output:

[2, 4, 8, 10]

Remove an Array Element Using the delete_if Method

There is also a delete_if method that deletes an element that matches a condition from an array. This also mutates the original array.

numbers = [2, 4, 6, 8, 10]
numbers.delete_if { |n| n == 6 }
puts numbers

Output:

[2, 4, 8, 10]

Note that reject! also modifies arrays in place and can be used similarly as delete_if.

numbers = [2, 4, 6, 8, 10]
numbers.reject! { |n| n == 6 }
puts numbers

Output:

[2, 4, 8, 10]

Related Article - Ruby Array