简体   繁体   中英

delete ONE array element by value in 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

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]

You can also use :- operator to remove desired element from the array, eg:

$> [1, 2, 3, '4', 'foo'] - ['foo']
$> [1, 2, 3, '4']

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM