Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete first instance of matching element from array

Tags:

arrays

ruby

Say I have the array [1,2,3,1,2,3] and I want to delete the first instance of (say) 2 from the array giving [1,3,1,2,3]. What's the easiest way?

like image 973
Nick Moore Avatar asked Jan 04 '11 15:01

Nick Moore


People also ask

How to remove first matching element from array in JavaScript?

Javascript remove first occurrence of a specific element from an array. Javascript's splice() method is used to modify the elements of an array. The splice() method can remove, replace or/and add new elements to the array. The above code uses the splice() method to delete only 1 occurrence of element 25.

How do I remove the first element from an array?

shift() The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

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.


2 Answers

li.delete_at(li.index(n) || li.length) 

li[li.length] is out of range, so the || li.length handles the case where n isn't in the list.

irb(main):001:0> li = [1,2,3,1,2,3] => [1, 2, 3, 1, 2, 3] irb(main):002:0> li.delete_at(li.index(2) || li.length) => 2 irb(main):003:0> li.delete_at(li.index(42) || li.length) => nil irb(main):004:0> li => [1, 3, 1, 2, 3] 
like image 74
moinudin Avatar answered Oct 20 '22 17:10

moinudin


If || li.length is to avoid sending nil to li.delete_at (which would result in a TypeError), then a more readable version might look like this

li.delete_at li.index(42) unless li.index(42).nil?

like image 43
autodidakto Avatar answered Oct 20 '22 16:10

autodidakto