Search code examples
arraysruby

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


In Ruby 2.4, how do I find the earliest index of an element of an array in another array? That is, if any element of an array occurs in the other array, I want to get the first index. I thought find_index might do it, but

a = ["a", "b", "c"]
# => ["a", "b", "c"]
a.find_index("a")
# => 0
a.find_index(["b", "c"])
# => nil

In the above example, I would expect to see the output "1" because the element "b" occurs at index 1 in the array "a".


Solution

  • find_index takes a single element. You could find the minimum by doing something like

    a = ["a", "b", "c"]
    to_find = ["b", "c"]
    to_find.map {|i| a.find_index(i) } .compact.min # => 1