How to delete a range of values from an array?

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

    You can try this

    [1, 2, 3, 4, 5, 6, 7, 8, 9].reject.with_index{|element,index| index >= 2 && index <= 5}
    => [1, 2, 7, 8, 9]
    

    or use delete_if

    [1, 2, 3, 4, 5, 6, 7, 8, 9].delete_if.with_index{|element,index| index >= 2 && index <= 5}
    => [1, 2, 7, 8, 9]
    

提交回复
热议问题