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
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]
find_index is included in the array, otherwise delete_at raises a TypeError because its argument is nil.arr.delete_at(arr.index(3) || arr.size).You can also use :- operator to remove desired element from the array, e.g.:
$> [1, 2, 3, '4', 'foo'] - ['foo']
$> [1, 2, 3, '4']
Hope this helps.
x = [1, 1]; x - [1] # => []. This does not answer the question, which was to explicitly "delete ONE array element by value".