Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a range of values from an array?

Tags:

arrays

ruby

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 the range 2..5 from that array, the result should be [1, 2, 7, 8, 9]

Thanks in advance.

like image 972
Guna Sekhar Avatar asked Nov 13 '14 12:11

Guna Sekhar


3 Answers

Use slice!:

Deletes the element(s) given by [...] a range.

array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
array.slice!(2..5)
array #=> [1, 2, 7, 8, 9]
like image 166
Stefan Avatar answered Oct 10 '22 14:10

Stefan


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]
like image 42
Data Don Avatar answered Oct 10 '22 13:10

Data Don


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]
like image 35
Gabriel de Oliveira Avatar answered Oct 10 '22 12:10

Gabriel de Oliveira