Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Selecting a set of array indices whose elements pass a test

Tags:

arrays

ruby

Ruby has a select method that takes an array and returns a subarray consisting of all the elements that pass the test given in a block:

myarray.select{|e| mytest(e)}   #=> subarray of elements passing mytest

I am wondering whether there is a simple method to get not these elements, but their indices. I understand you could do this:

indices = []
myarray.each_with_index{|e,i| indices << i if mytest(e)}

But I'm looking for a one-liner. Does one exist? Please don't write an extension to the Array class, I know you can get a one-liner that way.

like image 680
Sean Mackesey Avatar asked Jul 31 '26 02:07

Sean Mackesey


1 Answers

Another one-liner:

(0...myarray.length).select {|i| mytest(myarray[i])}

Cheers!

like image 74
Xavier Holt Avatar answered Aug 02 '26 15:08

Xavier Holt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!