delete ONE array element by value in ruby

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]

Tags:

Arrays

Ruby