简体   繁体   中英

Ruby array.each with non unique integer values

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?

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM