Reputation: 1477
We have array = [4, 2, 9, 11, 2, 16]
Then we have
indexes = []
for i in array do
if i > 0 then indexes << array.find_index(i) else next end
end
When printing out the result it returns
[0, 1, 2, 3, 1, 5]
The problem is with the fourth index. It should be 4, but it's 1 and that's because index 1 and 4 of array
have the same value (which is 2
).
Isn't for
loop (or .each
) supposed to go through all the elements one by one? Why is this happening? Why is it picking up second index of array
twice?
Upvotes: 1
Views: 126
Reputation: 62648
array.find_index
returns the first index of an element in array
matching the passed value.
If you want the index of the value you're looking for then you should be iterating with each_with_index:
indexes = []
array.each_with_index do |value, index|
indexes << index if value > 0
end
Or more compact (with just a single array allocation):
indexes = array.each_with_object([]).with_index {|(v, o), i| o << v if i > 0 }
Or allowing for multiple allocations:
indexes = array.map.with_index {|v, i| v > 0 ? i : nil }.compact
Or:
indexes.map.with_index.select {|v| v.first > 0 }.map(&:last)
Upvotes: 2
Reputation: 2045
Because Array#find_index returns the index of the first element it finds in the array.
Returns the index of the first object in ary such that the object is == to obj.
Upvotes: 1