Remove an Array Element in Ruby
-
Remove an Array Element Using the
reject
Method - Remove an Array Element Using the Array Subtraction
-
Remove an Array Element Using the
delete
Method -
Remove an Array Element Using the
delete_if
Method

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
- %i and %I in Ruby
- Combine Array to String in Ruby
- Square Array Element in Ruby
- Merge Arrays in Ruby
- Convert Array to Hash in Ruby
- Remove Duplicates From a Ruby Array