How can I delete one element from an array by value

前端 未结 15 1053
独厮守ぢ
独厮守ぢ 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 06:02

    Compiling all the different options for delete in ruby

    delete - Deletes matching elements by value. If more than one value matches it will remove all. If you don't care about the number of occurrence or sure about single occurrence, use this method.

    a = [2, 6, 3, 5, 3, 7]
    a.delete(3)  # returns 3
    puts a       # return [2, 6, 5, 7]
    

    delete_at - Deletes element at given index. If you know the index use this method.

    # continuing from the above example
    a.delete_at(2) # returns 5
    puts a         # returns [2, 6, 7]
    

    delete_if - Deletes every element for which block is true. This will modify the array. Array changes instantly as the block is called.

    b = [1, 2, 5, 4, 9, 10, 11]
    b.delete_if {|n| n >= 10}.  # returns [1, 2, 5, 4, 9]
    

    reject - This will return new array with the elements for which the given block is false. The ordering is maintained with this.

    c = [1, 2, 5, 4, 9, 10, 11]
    c.reject {|n| n >= 10}.  # returns [1, 2, 5, 4, 9]
    

    reject! - same as delete_if. Array may not change instantly as the block is called.

    If you want to delete multiple values from array, the best option is as bellow.

    a = [2, 3, 7, 4, 6, 21, 13]
    b = [7, 21]
    a = a - b    # a - [2, 3, 4, 6, 13]
    

提交回复
热议问题