Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing multiple elements from array by index in Ruby [duplicate]

Tags:

arrays

ruby

I have an array. For example,

x = [1,2,3,4,5]

I know the command

x.delete_at(i)

will delete the element at index i from the array. But from what I've read, it can only handle one argument.

Let's say I have a variable that stores the indexes I wish to remove from x. For example,

y = [0,2,3]

My question: Is it possible to remove multiple elements from an array using another array that stores in the indexes you wish to delete at?

In essence, something like

x.delete_at(y)

Thanks! :)

like image 701
MikamiHero Avatar asked Apr 12 '17 07:04

MikamiHero


People also ask

How do I remove multiple elements from an array?

Approach 1: Store the index of array elements into another array which need to be removed. Start a loop and run it to the number of elements in the array. Use splice() method to remove the element at a particular index.


1 Answers

You can use reject with with_index:

x.reject.with_index { |e, i| y.include? i } #=> [2, 5]
like image 57
Sagar Pandya Avatar answered Oct 26 '22 05:10

Sagar Pandya