How to compare strings ignoring the case

RubyStringString Comparison

Ruby Problem Overview


I want apple and Apple comparison to be true. Currently

"Apple" == "Apple"  # returns TRUE
"Apple" == "APPLE"  # returns FALSE

Ruby Solutions


Solution 1 - Ruby

You're looking for casecmp. It returns 0 if two strings are equal, case-insensitively.

str1.casecmp(str2) == 0

"Apple".casecmp("APPLE") == 0
#=> true

Alternatively, you can convert both strings to lower case (str.downcase) and compare for equality.

Solution 2 - Ruby

In Ruby 2.4.0 you have: casecmp?(other_str) → true, false, or nil

"abcdef".casecmp?("abcde")     #=> false
"aBcDeF".casecmp?("abcdef")    #=> true
"abcdef".casecmp?("abcdefg")   #=> false
"abcdef".casecmp?("ABCDEF")    #=> true

Here you have more info

Solution 3 - Ruby

In case you have to compare UTF-8 strings ignoring case:

>> str1 = "Мария"
=> "Мария"
>> str2 = "мария"
=> "мария"
>> str1.casecmp(str2) == 0
=> false
>> require 'active_support/all'
=> true
>> str1.mb_chars.downcase.to_s.casecmp(str2.mb_chars.downcase.to_s) == 0
=> true

It works this way in Ruby 2.3.1 and earlier versions.

For smaller memory footprint you can cherry pick string/multibyte:

require 'active_support'
require 'active_support/core_ext/string/multibyte'

Edit, Ruby 2.4.0:

>> str1.casecmp(str2) == 0
=> false

So casecmp doesn't work in 2.4.0; However in 2.4.0 one can compare UTF-8 strings manually without active_support gem:

>> str1.downcase == str2.downcase
=> true

Solution 4 - Ruby

For ruby 2.4 working fine casecmp? for utf-8 strings (mb_chars not needed):

2.4.1 :062 > 'строка1'.casecmp?('СтроКа1')
 => true

but casecmp isn't workin for utf-8:

2.4.1 :062 > 'строка1'.casecmp('СтроКА1')
 => 1
2.4.1 :063 > 'string1'.casecmp('StrInG1')
 => 0

Solution 5 - Ruby

casecmp and zero? are ruby inbuilt methods. casecmp returns 0 if two strings are equal, case-insensitively and zero? checks for zero value (==0)

str1.casecmp(str2).zero?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStevenView Question on Stackoverflow
Solution 1 - RubymolfView Answer on Stackoverflow
Solution 2 - RubyAndresView Answer on Stackoverflow
Solution 3 - RubyAdobeView Answer on Stackoverflow
Solution 4 - RubySergio BelevskijView Answer on Stackoverflow
Solution 5 - RubySivalingamView Answer on Stackoverflow