Get index of array element faster than O(n)

前端 未结 8 1342
春和景丽
春和景丽 2020-12-07 09:28

Given I have a HUGE array, and a value from it. I want to get index of the value in array. Is there any other way, rather then call Array#index to get it? The p

8条回答
  •  不知归路
    2020-12-07 10:00

    Convert the array into a hash. Then look for the key.

    array = ['a', 'b', 'c']
    hash = Hash[array.map.with_index.to_a]    # => {"a"=>0, "b"=>1, "c"=>2}
    hash['b'] # => 1
    

提交回复
热议问题