在Ruby中如何更换重音拉丁字符的? [英] How do I replace accented Latin characters in Ruby?
问题描述
我有一个的ActiveRecord
模式,富
,其中有一个名称
字段。我希望用户能够按名称搜索,但我想搜索忽略大小写和任何口音。因此,我还存储 canonical_name
针对其搜索领域:
I have an ActiveRecord
model, Foo
, which has a name
field. I'd like users to be able to search by name, but I'd like the search to ignore case and any accents. Thus, I'm also storing a canonical_name
field against which to search:
class Foo
validates_presence_of :name
before_validate :set_canonical_name
private
def set_canonical_name
self.canonical_name ||= canonicalize(self.name) if self.name
end
def canonicalize(x)
x.downcase. # something here
end
end
我需要填写的东西在这里来代替重音符号。有什么比
I need to fill in the "something here" to replace the accented characters. Is there anything better than
x.downcase.gsub(/[àáâãäå]/,'a').gsub(/æ/,'ae').gsub(/ç/, 'c').gsub(/[èéêë]/,'e')....
和,对于这个问题,因为我不是在Ruby 1.9的,我不能把这些统一code文字在我的code。实际经常EX pressions会显得更恶心。
And, for that matter, since I'm not on Ruby 1.9, I can't put those Unicode literals in my code. The actual regular expressions will look much uglier.
推荐答案
Rails有已经一个内建的正火,你只需要使用这个标准化的字符串,形成KD和删除其他字符是这样的:
Rails has already a builtin for normalizing, you just have to use this to normalize your string to form KD and remove the other chars like this:
>> "àáâãäå".chars.normalize(:kd).gsub(/[^\x00-\x7F]/n,'').downcase.to_s
=> "aaaaaa"
这篇关于在Ruby中如何更换重音拉丁字符的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!