{

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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

How to Convert current Unix timestamp epoch to DateTime in Ruby Programming| Ruby on Rails by Example

How to check the type of a variable is Ruby| Ruby on Rails By Example

How to print the name of a Ruby class| Ruby on Rails By Example

How to check if the variable is defined in Ruby with examples

How to Find the minimum and maximum values in an array and hash Ruby with examples

How to Generate Random number in Ruby with examples

How to Get current Unix timestamp or milliseconds since epoch Ruby Programming| Ruby on Rails by Example