Find indices of elements that match a given condition

后端 未结 6 1459
小蘑菇
小蘑菇 2020-11-28 09:11

Given an array, how can I find all indices of elements those match a given condition?

For example, if I have:

arr = [\'x\', \'o\', \'x\', \'.\', \'.\         


        
6条回答
  •  温柔的废话
    2020-11-28 09:30

    Not sure if you consider this an improvement or not, but using (map + compact) as a filter feels very clunky to me. I would use select, since that's what it's for, and then just grab the part of the result I care about:

    arr.each_with_index.select { |a,i| a == 'x' }.map &:last
    

提交回复
热议问题