How to delete a range of values from an array?

前端 未结 5 1977
走了就别回头了
走了就别回头了 2021-01-02 07:46

If array = [1, 2, 3, 4, 5, 6, 7, 8, 9], I want to delete a range of elements from array.

For example: I want to delete all elements with an index in th

5条回答
  •  不知归路
    2021-01-02 08:24

    Delete When Range Includes Value

    One of the many ways to do this is to invoke Array#delete_if with a block that checks whether each element of the Array is included in the Range with Array#include?. For example:

    array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    array.delete_if { |i| (2..5).include? i }
    #=> [1, 6, 7, 8, 9]
    

提交回复
热议问题