Reputation: 22225
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?
Upvotes: 0
Views: 79
Reputation: 369428
Another possible alternative:
my_array.select.with_index {|elem, _| cond(elem) }.map(&:last)
Upvotes: 3
Reputation: 52357
Nope, there is nothing inbuilt or much simpler that what you already got.
Variation:
my_array.each_with_index.with_object([]) do |(elem, idx), indices|
indices << idx if cond(elem)
end
Upvotes: 4
Reputation: 29094
You can use Array#each_index with select
arr = [1, 2, 3, 4]
arr.each_index.select {|i| arr[i].odd? }
# => [0, 2]
Upvotes: 2