12

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.

2
  • 2..5 is the index range not values Commented Nov 13, 2014 at 12:58
  • Your question is unclear. What do you really want to do? Remove values at indices 2..5, which is 2,3,4, and 5? or you want to remove those values which matches on or between 2..5? Commented Nov 13, 2014 at 13:05

5 Answers 5

26

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]
Sign up to request clarification or add additional context in comments.

4 Comments

Yours is sweet and simple. I almost forgot slice!
This should include 2 and not include 5?
@Зелёный indices 2..5 refer to values 3, 4, 5 and 6.
Good solution, Stefan. I would be stunned well and truely if the downvoter came forward to defend his/her black mark.
3

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]

Comments

1

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]

Comments

1

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]

1 Comment

Why post two separate answers? There is an "edit" link.
-1

Delete Array Elements by Index from Range

If you are trying to delete elements by index rather than by value, one way to solve this is to iterate over your Range object, invoking Array#delete_at for each index in the range. For example:

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

2 Comments

Why post two separate answers? There is an "edit" link.
This does not work, array.delete_at is mutating the array while you are iterating.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.