Get index of array element faster than O(n)
Why not use index or rindex?
array = %w( a b c d e)# get FIRST index of element searchedputs array.index('a')# get LAST index of element searchedputs array.rindex('a')
index: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-index
rindex: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-rindex
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
Other answers don't take into account the possibility of an entry listed multiple times in an array. This will return a hash where each key is a unique object in the array and each value is an array of indices that corresponds to where the object lives:
a = [1, 2, 3, 1, 2, 3, 4]=> [1, 2, 3, 1, 2, 3, 4]indices = a.each_with_index.inject(Hash.new { Array.new }) do |hash, (obj, i)| hash[obj] += [i] hashend=> { 1 => [0, 3], 2 => [1, 4], 3 => [2, 5], 4 => [6] }
This allows for a quick search for duplicate entries:
indices.select { |k, v| v.size > 1 }=> { 1 => [0, 3], 2 => [1, 4], 3 => [2, 5] }