Ruby on Rails: compare two strings in terms of database collation

只谈情不闲聊 提交于 2019-12-23 17:27:42

问题


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

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.

The problem is database collation.

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

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

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).

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


回答1:


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

Hope that helps!

Zubin



来源:https://stackoverflow.com/questions/5353690/ruby-on-rails-compare-two-strings-in-terms-of-database-collation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!