How can I delete one element from an array by value

前端 未结 15 998
独厮守ぢ
独厮守ぢ 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:12

    If you also want to make this deletion operation chainable, so you can delete some item and keep on chaining operations on the resulting array, use tap:

    [2, 4, 6, 3, 8].tap { |ary| ary.delete(3) }.count #=> 4
    
    0 讨论(0)
  • 2020-12-04 06:13

    I think I've figured it out:

    a = [3, 2, 4, 6, 3, 8]
    a.delete(3)
    #=> 3
    a
    #=> [2, 4, 6, 8]
    
    0 讨论(0)
  • 2020-12-04 06:19

    I like the -=[4] way mentioned in other answers to delete the elements whose value are 4.

    But there is this way:

    irb(main):419:0> [2,4,6,3,8,6].delete_if{|i|i==6}
    => [2, 4, 3, 8]
    irb(main):420:0>
    

    mentioned somewhere in "Basic Array Operations", after it mentions the map function.

    0 讨论(0)
提交回复
热议问题