Topic: [Share]Case Insensitive String Search
As Ruby On Rails developer, we all know that we can search through a string using include? method. Unfortunately this method is case sensitive. If you're developing a web application which has searching feature , it will be a bugs if your searching feature is case sensitive. For example, check out the code below.
"hello".include? "H" # will return false
So, how to use include? method in Rails without its case sensitivity ? Is it possible? Yes, it is. Here's the way to do it.
To avoid case sensitive when using include? method in Rails, you should combine this method with another method. Its name is downcase. To combine include? method with downcase, you can do that like this one.
"hello".downcase.include? "H".downcase # will return true
Curious about the logic of the above codes ? The logic is simple:
Supposed that "hello" is based string where we want to search through it (this is just the example, the real case may much more complicated string)
Supposed that "H" is the keyword submitted by the user on view side (remember MVC architecture)
First, we change all letters in "hello" into downcase. So if the based string is "Hello", "HELLO", or "hElLo", it won't be a matter. It will be converted to "hello".
Second, we change all letters in "H" into downcase. So if user submitted "H" or "h" , it won't be a matter. It will be converted to "h".
You can use the codes above to search string inside an array. You just have to do a loop through that array and check each of its element. As long as its element is string, you can use the codes above. But if your array contains another element , you need to add more logic.