How to remove an element from an array in Ruby Programming| Ruby on Rails by Example

How to remove an element from an array in Ruby?

There are multiple ways we can delete from an array in Ruby.

  • array delete method
  • array delete_at
  • Minus operator
  • delete_if

remove an element from an array using the delete method

Array delete method removes an element if found, else returns nil.

Here is an example code

array = [1, 2, 3, 4, 5, 6]
array.delete(3)
puts array

Output:

1
2
4
5
6

use substraction operator

subtraction operator or minus symbol removes the element from an array and returns the result.

Here is an example code

array = [1, 2, 3, 4, 5, 6]
puts array-[1] #2 3 4 5 6
array -= [4]
puts array  #1 2 3 5 6

remove element using an index from an array

This is an example of removing an element from an array with an index. First, check the index of an element using an array. index method. the index always starts with 0 and length-1. Next, call array.delete_at method to remove an element with index.

Here is an example

array = [1, 2, 3, 4, 5, 6]
array.delete_at(array.index(5))
puts array  #1 2 3 6

remove element using a conditional element from an array

Sometimes, we want to do a conditional statement to check the element and remove it.

It is not useful for an array of primitive values, Can be used with hashes to check if property value matched, and remove a hash from an array.

Here is an example in Ruby

array = [1, 2, 3, 4, 5, 6]
array.delete_if { |i| i == 5 }
puts array  #1 2 3 4 6

This approach is used to remove a hash from an array based on hash values.

Conclusion

To summarize, Learned multiple ways to remove an element from an array.