How to Delete Items from Arrays in Ruby
Now that we know how to create an array and add elements to it, we are now going to see how to delete items from it.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

Now that we know how to create an array and add elements to it, we are now going to see how to delete items from an array.

Let's start by creating an array. In Ruby, an array can contain elements of different data types so we'll build an array that contains: strings, integers, and booleans.

x = ["asdf", 3, 4, 12, "asdf", "b", true, 34, 2, 4, 4, 4]

If I want to delete all the 4 values from the array, we can run the following code:

x.delete(4)

If you print x, you can see all elements except 4's.

You can check the length of the array before and after. When you place x.length before the delete method, your array will return a value of 12. And if you run the length method after deleting the values of 4, your array's length will only be 8.

Now if I want to remove the number 12 which is the third element in the array, I can delete it with this code:

x.delete_at(2)

devCamp Note: the 12 was the third element in the array after removing the 4's from the array. Also remember that arrays start by counting at 0.

An important item to understand when using the delete_at method is that when you use this method, it not only deletes 12, but also returns it. So, if you ever need the value of the element that was deleted from the array, you can get it from this method. In fact, this is a practical function that you are sure to use it while creating applications.

For example, if you want to store a value that was removed from the array, I can do something like this.

y = x.delete_at(4)

Now, my y variable will have the value true even if this value is no longer present in the array.

There is one more way to delete an element based on a specific condition. Let's examine it with a real-world example.

batting_averages = [0.3, 0.18, 0.22, 0.25]

Now, if I want to delete all the values that are under a certain average, I can run the code:

batting_averages.delete_if { |average| average < 0.24}

In this code, I'm using a function called delete_if, which takes a block. Essentially this iterates through the array with the block variable average and it will delete all the values that are less than 0.24. So, my output should only have two elements left in the array, which are, 0.3 and 0.25.

So, these are the different ways to delete elements from an array.