Delete one element of an array by value in ruby

How can I remove the first element by value in an array?

arr = [ 1, 1, 2, 2, 3, 3, 4, 5 ] #something like: arr.delete_first(3) #I would like a result like => [ 1, 1, 2, 2, 3, 4, 5] 

thank you in advance

+7
source share
2 answers

Pass the result of Array#find_index to Array#delete_at :

 >> arr.delete_at(arr.find_index(3)) >> arr => [1, 1, 2, 2, 3, 4, 5] 

find_index() will return the index of the array of the first element that matches its argument. delete_at() removes an element from the array at the specified index.

To prevent delete_at() raising a TypeError if the index is not found, you can use the && construct to assign the result of find_index() variable and use this variable in delete_at() if it is not nil . The right side && will not be executed at all if the left side is false or nil .

 >> (i = arr.find_index(3)) && arr.delete_at(i) => 3 >> (i = arr.find_index(6)) && arr.delete_at(i) => nil >> arr => [1, 1, 2, 2, 3, 4, 5] 
+18
source

You can also use the operator :- to remove the desired element from the array, for example:

 $> [1, 2, 3, '4', 'foo'] - ['foo'] $> [1, 2, 3, '4'] 

Hope this helps.

-7
source

Source: https://habr.com/ru/post/950441/


All Articles