Find indices of elements that match a given condition

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

    Another way:

    arr.size.times.select {|i| arr[i] == 'x'} # => [0, 2, 6]
    

    EDIT:

    Not sure if this is even needed, but here they are.

    Benchmarks:

    arr = 10000000.times.map{rand(1000)};
    
    Benchmark.measure{arr.each_with_index.map { |a, i| a == 50 ? i : nil }.compact}
    2.090000   0.120000   2.210000 (  2.205431)
    
    Benchmark.measure{(0..arr.size-1).select { |i| arr[i] == 50 }}
    1.600000   0.000000   1.600000 (  1.604543)
    
    Benchmark.measure{arr.map.with_index {|a, i| a == 50 ? i : nil}.compact}
    1.810000   0.020000   1.830000 (  1.829151)
    
    Benchmark.measure{arr.each_index.select{|i| arr[i] == 50}}
    1.590000   0.000000   1.590000 (  1.584074)
    
    Benchmark.measure{arr.size.times.select {|i| arr[i] == 50}}
    1.570000   0.000000   1.570000 (  1.574474)
    

提交回复
热议问题