How can I delete one element from an array by value

前端 未结 15 1066
独厮守ぢ
独厮守ぢ 2020-12-04 05:16

I have an array of elements in Ruby

[2,4,6,3,8]

I need to remove elements with value 3 for example

How do I do that?<

15条回答
  •  囚心锁ツ
    2020-12-04 05:54

    I'm not sure if anyone has stated this, but Array.delete() and -= value will delete every instance of the value passed to it within the Array. In order to delete the first instance of the particular element you could do something like

    arr = [1,3,2,44,5]
    arr.delete_at(arr.index(44))
    
    #=> [1,3,2,5]
    

    There could be a simpler way. I'm not saying this is best practice, but it is something that should be recognized.

提交回复
热议问题