I want to know what’s the best way to make the String.include? methods ignore case. Currently I’m doing the following. Any suggestions? Thanks!
a = "abcDE"
b = "CD"
result = a.downcase.include? b.downcase
Edit:
How about Array.include?. All elements of the array are strings.
Summary
If you are only going to test a single word against an array, or if the contents of your array changes frequently, the fastest answer is Aaron’s:
If you are going to test many words against a static array, it’s far better to use a variation of farnoy’s answer: create a copy of your array that has all-lowercase versions of your words, and use
include?. (This assumes that you can spare the memory to create a mutated copy of your array.)Even better, create a
Setfrom your array.My original answer below is a very poor performer and generally not appropriate.
Benchmarks
Following are benchmarks for looking for 1,000 words with random casing in an array of slightly over 100,000 words, where 500 of the words will be found and 500 will not.
any?.any?from my comment.Setfrom the array of downcased strings, once before testing.If you can create a single downcased copy of your array once to perform many lookups against, farnoy’s answer is the best (assuming you must use an array). If you can create a
Set, though, do that.If you like, examine the benchmarking code.
Original Answer
I (originally said that I) would personally create a case-insensitive regex (for a string literal) and use that:
Using
any?can be slightly faster thangrepas it can exit the loop as soon as it finds a single match.