开发者

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

开发者 https://www.devze.com 2023-02-18 04:34 出处:网络
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

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 i开发者_开发知识库n terms of the same collation?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消