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?
for..endsyntax is preferred. It is identical toarray.eachthough more verbose and some subtle scope differences that may get you in trouble someday. Theelse nexthas no effect either.array = [0, 2, 9, 0, 2, 16]; array.each_index.reject { |i| array[i].zero? } #=> [1, 2, 4, 5].