Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, is there a way to remove only 1 match in an Array easily?

Tags:

In Ruby, the array subtraction or reject

>> [1,3,5,7,7] - [7]
=> [1, 3, 5]

>> [1,3,5,7,7].reject{|i| i == 7}
=> [1, 3, 5]

will remove all entries in the array. Is there an easy to remove just 1 occurrence?

like image 527
nonopolarity Avatar asked Jan 19 '11 03:01

nonopolarity


People also ask

How do you remove one element from an array in Ruby?

Ruby | Array delete() operation 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 you slice an array in Ruby?

slice() in Ruby? The array. slice() is a method in Ruby that is used to return a sub-array of an array. It does this either by giving the index of the element or by providing the index position and the range of elements to return.

What does .last do in Ruby?

The . last property of an array in Ruby returns the last element of the array.

How to remove the first and last element of an array?

To remove the first element of an array,we need to use Array.shift or Array.shift () command. Here is my example using the Array A. A.shift () should remove the first element of A which is 1 and it should return A = [2,3,4,5,6] To remove the last element of an array,we can use the Array.pop or Array.pop () command.

How to remove first occurance of a repeating value from array?

The command is Array.delete_at (Array.index (value)) will remove the first occurance of a repeating value from the array. I have applied that to A below.

How to remove a repeating value from an array in JavaScript?

You need to use Array.delete (value) . The command will remove all the elements of the array which matches the value. So be careful with it. If you just want to remove the first occurance of a repeating value, please read the next tutorial. Here is my example using Array A I need to remove the value 3 from my array. So I call A.delete (3).

How to remove elements from an array in JavaScript?

Here also, you don't need to pass any argument because whichever element is found by the method as the first element will be removed. In the article, we will discuss two more such methods which will help us to remove the elements from the Array and they are namely Array.delete () and Array.delete_at ().


1 Answers

>> a = [1,3,5,7,7]

>> a.slice!(a.index(7))
=> 7

>> a
=> [1,3,5,7]
like image 113
mbm Avatar answered Jan 03 '23 16:01

mbm