Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing elements from array Ruby

Tags:

arrays

ruby

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?

like image 606
Michael Avatar asked Jan 19 '12 15:01

Michael


People also ask

How do I remove an element from an array in Ruby?

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.

How do I remove a string from an array in Ruby?

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.

How do you remove the first element from an array in Ruby?

You can use Array. delete_at(0) method which will delete first element.


1 Answers

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]

like image 75
Norm212 Avatar answered Sep 21 '22 19:09

Norm212