Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete ONE array element by value in ruby

Tags:

arrays

ruby

How can I delete the first element by a 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]

Thanks in advance

like image 946
hcarreras Avatar asked Jul 27 '13 23:07

hcarreras


People also ask

How do I remove a specific 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 remove an element from an array with value?

We can use the following JavaScript methods to remove an array element by its value. indexOf() – function is used to find array index number of given value. Return negavie number if the matching element not found. splice() function is used to delete a particular index value and return updated array.

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

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

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


1 Answers

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

>> arr.delete_at(arr.find_index(3))

>> arr
=> [1, 1, 2, 2, 3, 4, 5]

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

To prevent delete_at() raising a TypeError if the index isn't found, you may use a && construct to assign the result of find_index() to a variable and use that variable in delete_at() if it isn't nil. The right side of && won't execute 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]
like image 198
Michael Berkowski Avatar answered Oct 31 '22 22:10

Michael Berkowski