How to compare strings ignoring the case

后端 未结 5 685
名媛妹妹
名媛妹妹 2020-12-04 20:53

I want apple and Apple comparison to be true. Currently

\"Apple\" == \"Apple\"  # returns TRUE
\"Apple\" == \"APPLE\"          


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 21:17

    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
    

提交回复
热议问题