2

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.

2 Answers2

3

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?

Community
  • 1
  • 1
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
0

If you know the string contains all upper case letters, you can use the method upcase to convert the string to uppercase as such:

2.3.0 :001 > a = ["A", "B", "C"]
 => ["A", "B", "C"] 
2.3.0 :002 > a.index("b".upcase)
 => 1 
2.3.0 :003 > tmp = "c"
 => "c" 
2.3.0 :004 > a.index(tmp.upcase)
 => 2 
Dom
  • 1,687
  • 6
  • 27
  • 37