Find indices of elements that match a given condition

后端 未结 6 1453
小蘑菇
小蘑菇 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:46

    A slight improvement over your each_with_index.map line

    arr.map.with_index {|a, i| a == 'x' ? i : nil}.compact # => [0, 2, 6]
    

提交回复
热议问题