I have an array, and I need an array of subscripts of the original array's elements that satisfy a certain condition.
map doesn't do because it yields an array of the same size. select doesn't do because it yields references to the individual array elements, not their indices. I came up with the following solution:
my_array.map.with_index {|elem,i| cond(elem) ? i : nil}.compact If the array is large and only a few elements fulfill the conditions, another possibility would be
index_array=[] my_array.each_with_index {|elem,i| index_array << i if cond(elem)} Both work, but isn't there a simpler way?
my_array.map.with_index {|elem,i| cond(elem) ? i : nil}.compactcould be simplified tomy_array.map.with_index {|elem,i| i if cond(elem)}.compactbut it is essentially the same