Search code examples
arraysrubyindexofcase-insensitive

In Ruby, how do I find the index of an element in an array in a case-insensitive way?


I’m using Ruby 2.3. I’m able to find the index of an element in an array using

2.3.0 :001 > a = ["A", "B", "C"]
 => ["A", "B", "C"] 
2.3.0 :003 > a.index("B")
 => 1 

but how would I do it if I wanted to find the index of the element in a case-insensitive way? E.g., I could do

2.3.0 :003 > a.index(“b”)

and get the same result as above? You can assume that if all the elements were upper-cased, there won’t be two of the same element in the array.


Solution

  • Use Array#find_index:

    a = ["A", "B", "C"]
    a.find_index {|item| item.casecmp("b") == 0 }
    # or
    a.find_index {|item| item.downcase == "b" }
    

    Note that the usual Ruby caveats apply for case conversion and comparison of accented and other non-Latin characters. This will change in Ruby 2.4. See this SO question: Ruby 1.9: how can I properly upcase & downcase multibyte strings?