Ruby on Rails:比较两个字符串的数据库排序规则 [英] Ruby on Rails: compare two strings in terms of database collation

查看:77
本文介绍了Ruby on Rails:比较两个字符串的数据库排序规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of words and want to find which ones already exist in the database.

我决定使用 SELECT,而不是进行数十个SQL查询。 word table word IN(array_of_words)的位置和然后遍历结果。

Instead of making tens of SQL queries, I decided to use "SELECT word FROM table WHERE word IN(array_of_words)" and then loop through the result.

问题是数据库整理。

http://www.collat​​ion-charts.org/mysql60/mysql604.utf8_general_ci.european.html

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

There are many different characters, which MySQL treats as the same. However, in Ruby code string1 would not be equal to string2.

例如:如果单词为šuo,则如果找到,数据库也可能返回 suo (而且还可以),但是,当我要检查时,如果找到šuo的东西,Ruby当然会返回false(šuo!= suo)。

For example: if the word is "šuo", database might also return "suo", if it's found (and it's ok), but, when I want to check, if something by "šuo" is found, Ruby, of course, returns false (šuo != suo).

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

So, is there any way to compare two strings in Ruby in terms of the same collation?

推荐答案

我用过iconv类似于以下内容:

I've used iconv like this for something similar:

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

希望有帮助!

Zubin

这篇关于Ruby on Rails:比较两个字符串的数据库排序规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆