How to delete a range of values from an array?

前端 未结 5 1933
走了就别回头了
走了就别回头了 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:21

    As Stefan posted, use slice! to remove values located inside a certain range in the array. If what you need, however, is to remove values that are within a certain range use delete_if.

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

提交回复
热议问题