【问题标题】:Ruby on Rails: compare two strings in terms of database collationRuby on Rails:根据数据库排序比较两个字符串
【发布时间】:2011-07-18 05:50:27
【问题描述】:

我有一个单词列表,想找出数据库中已经存在的单词。

我决定使用“SELECT word FROM table WHERE word IN(array_of_words)”而不是进行数十个 SQL 查询,然后循环遍历结果。

问题是数据库整理。

http://www.collation-charts.org/mysql60/mysql604.utf8_general_ci.european.html

有许多不同的字符,MySQL 将它们视为相同。但是,在 Ruby 代码中,string1 不等于 string2。

例如:如果单词是“šuo”,如果找到的话,数据库也可能返回“suo”(没关系),但是,当我想检查时,如果找到“šuo”的东西,Ruby,当然,返回 false (šuo != suo)。

那么,有没有办法在 Ruby 中根据相同的排序规则比较两个字符串?

【问题讨论】:

    标签: ruby-on-rails ruby collation


    【解决方案1】:

    我用这样的 iconv 来做类似的事情:

    require 'iconv'
    
    class String
      def to_ascii_iconv
        Iconv.new('ASCII//IGNORE//TRANSLIT', 'UTF-8').iconv(self).unpack('U*').select { |cp| cp < 127 }.pack('U*')
      end
    end
    
    puts 'suo'.to_ascii_iconv
    # => suo
    puts 'šuo'.to_ascii_iconv
    # => suo
    puts 'suo'.to_ascii_iconv == 'šuo'.to_ascii_iconv
    # => true
    

    希望有帮助!

    祖宾

    【讨论】:

    • 但是我如何知道根据数据库的排序规则使用哪种转换? ://
    猜你喜欢
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    相关资源
    最近更新 更多