Find indices of elements that match a given condition

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

    Ruby 1.9:

    arr = ['x', 'o', 'x', '.', '.', 'o', 'x']
    p arr.each_index.select{|i| arr[i] == 'x'} # =>[0, 2, 6]
    

    Code

提交回复
热议问题