Looking for a "method to erase a particular element" in an array?
In this article, I will introduce the corresponding delete () and delete_if!
We will explain it as carefully as possible for Ruby beginners, so please stay with us until the end!
First, I will introduce delete () that can delete the specified element.
This method can delete the element that matches the argument from the array just by specifying the element you want to delete as an argument.
delete()How to use
a = [1, 2, 3, 1, 2, 3]
#Remove only 3 elements from the array
a.delete(3)
a #=> [1, 2, 1, 2]
The above is an example of using delete ().
First, pass an array as an argument to a, and instruct a to delete the element 3 using the delete () method.
And when executed correctly, the result is as above.
Next, I will explain about delete_if.
delete_if can delete a wide range of array elements compared to delete ().
For example, suppose you want to remove only odd elements in an array.
a = [1, 2, 3, 1, 2, 3]
#Remove only odd elements from the array
a.delete_if do |n|
n.odd?
end
a #=> [2, 2]
First, prepare an array.
It then commands delete_if to delete the element if it is odd.
As a result, odd numbers are removed.
It is convenient to remember such a method when you want to operate an array in a terminal etc.
It's a method that beginners tend to forget, so if you remember it, you might be able to differentiate yourself from others!
I'm thinking of taking up such information as an article from now on, so I hope you'll see it if you like!
see you!
Recommended Posts