In Ruby, the array subtraction or reject
>> [1,3,5,7,7] - [7]
=> [1, 3, 5]
>> [1,3,5,7,7].reject{|i| i == 7}
=> [1, 3, 5]
will remove all entries in the array. Is there an easy to remove just 1 occurrence?
In Ruby, the array subtraction or reject
>> [1,3,5,7,7] - [7]
=> [1, 3, 5]
>> [1,3,5,7,7].reject{|i| i == 7}
=> [1, 3, 5]
will remove all entries in the array. Is there an easy to remove just 1 occurrence?
>> a = [1,3,5,7,7]
>> a.slice!(a.index(7))
=> 7
>> a
=> [1,3,5,7]
The best I can think of is:
found = false
[1,3,5,7,7].reject{|i| found = true if !found && i == 7}
Or destructively:
arr = [1, 2, 3, 5, 7, 7]
arr.delete_at( arr.index(7))
arr #=> [1, 2, 3, 5, 7]
While it doesn't directly answer your question, uniq
might be what you want.
[1,3,5,7,7].uniq # => [1,3,5,7]