1

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?

2
  • 1
    I would strongly suggest using modern syntax. There are very few cases that for..end syntax is preferred. It is identical to array.each though more verbose and some subtle scope differences that may get you in trouble someday. The else next has no effect either. Commented Oct 13, 2018 at 10:37
  • 1
    array = [0, 2, 9, 0, 2, 16]; array.each_index.reject { |i| array[i].zero? } #=> [1, 2, 4, 5]. Commented Oct 13, 2018 at 18:57

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Do you even refactor!? :) Nice one! But last answer is the most slick but you should call it on the array object array.map.with_index.select {|v| v.first > 0 }.map(&:last) or it just returns []
Alternatively for your last example use select { |a, _| a.positive? }.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.