9

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

2 Answers 2

22

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]
Sign up to request clarification or add additional context in comments.

5 Comments

You should check that that the argument of find_index is included in the array, otherwise delete_at raises a TypeError because its argument is nil.
@toro2k Indeed. Alternative added above which avoids the TypeError
A more compact way could be arr.delete_at(arr.index(3) || arr.size).
@toro2k That's why Ruby is such a neat language.
@steenslag sorry for the typo.. find_index() and index() are aliases of each other I believe. Their source is identical in the docs.
-8

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.

2 Comments

sadly this will delete all instances of 'foo' from the array
x = [1, 1]; x - [1] # => []. This does not answer the question, which was to explicitly "delete ONE array element by value".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.