Reinier Reinier - 11 months ago 38
Ruby Question

How can I delete certain indeces defined in an array from an other array in ruby

I have a method that iterates over an array, does a bunch of stuff under certain conditions and depending on these conditions I would ALSO like to delete some of the elements. In order to keep track of the indexes I like to delete I converted the each in to an each_with_index loop and store the index of the elements that I like to delete in an array index_array. How can I delete exactly the items on those indexes in my original array? Looping over the index_array and using delete_at would change the original index. Please see below description of the scenario:

> my_array = [0,1,2,3,4,5,6,7]
> delete_these_indexes = [1,2,5]
the desired result is:
> my_array => [0,3,4,6,7,8]


How about this?

my_array = [0, 1, 2, 3, 4, 5, 6, 7]
delete_these_indices = [1, 2, 5]

delete_these_indices.sort.reverse_each {|i| my_array.delete_at(i) }

p my_array
# => [0, 3, 4, 6, 7, 8]

It's important to delete from the end of the array, since deleting an item will change the indices of all subsequent items, ergo sort.reverse_each. If you know the array is already sorted, you can just do reverse_each.

If you don't care bout modifying the delete_these_indices array, you can be somewhat more terse:

my_array.delete_at(i) while (i = delete_these_indices.pop)

Again, you can skip sort! if you know delete_these_indices is already sorted.