In Ruby how do I find the index of one of an array of elements?

You can use find_index and pass the needed value from the array:

a = ["a", "b", "c"]
p a.find_index('a')
p a.find_index('b')
p a.find_index('c')
# => 0
# => 1
# => 2

You can use map to get every element inside your a array and then to get the index corresponding to each element:

p a.map{|e| a.find_index(e)}
# => [0, 1, 2]

Another possible way to handle it could be to use the Enumerable#each_with_index:

a.each_with_index{|e,i| puts "Element: #{e}, Index: #{i}"}
# => Element: a, Index: 0
# => Element: b, Index: 1
# => Element: c, Index: 2

If you want to check the indexes for each element in ["b", "c"] using the ["a", "b", "c"] array, you can map the first one, get the array values, and then use the a,b,c to check those indexes:

p ["b", "c"].map{|e| ["a", "b", "c"].find_index(e) }
# => [1, 2]

You can also see Array#index and Enumerable#find_index.

Leave a Comment

tech