Let's say I am trying to remove elements from array a = [1,1,1,2,2,3]
. If I perform the following:
b = a - [1,3]
Then I will get:
b = [2,2]
However, I want the result to be
b = [1,1,2,2]
i.e. I only remove one instance of each element in the subtracted vector not all cases. Is there a simple way in Ruby to do this?
Array#delete() : delete() is a Array class method which returns the array after deleting the mentioned elements. It can also delete a particular element in the array. Syntax: Array. delete() Parameter: obj - specific element to delete Return: last deleted values from the array.
Using delete_if# method The delete_if method accepts a conditional and removes all the elements in the array that do not meet the specified condition. The method takes a block and evaluates each element for a matching case. If the value does not meet the set conditions, the method removes it.
You can use Array. delete_at(0) method which will delete first element.
You may do:
a= [1,1,1,2,2,3] delete_list = [1,3] delete_list.each do |del| a.delete_at(a.index(del)) end
result : [1, 1, 2, 2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With