如何在 UTF-8 字符上使用 String 方法? [英] How do I use String methods on UTF-8 characters?
问题描述
如何在 UTF-8 字符上使用 String 方法?
How do I use String methods on UTF-8 characters?
例如,我有一个包含 Cyrillic 字符的字符串,所以当我使用 string.upcase
时它不起作用.
For example, I have a string with Cyrillic characters, so when I use string.upcase
it doesn't work.
推荐答案
Ruby 仅支持字母 A
–Z
和 a的大小写转换代码>–
z
.
Ruby only supports case conversions on the letters A
–Z
and a
–z
.
原因很简单,其他字母的大小写转换没有明确定义.例如,在土耳其语中 'I'.downcase # =>'ı'
和 'i'.upcase # =>'İ'
,但在法语 'I'.downcase # =>'i'
和 'i'.upcase # =>'我'
.Ruby 不仅要知道字符编码,还要知道正确编码的语言.
The reason for this is simply that case conversions for other letters aren't well defined. For example, in Turkish 'I'.downcase # => 'ı'
and 'i'.upcase # => 'İ'
, but in French 'I'.downcase # => 'i'
and 'i'.upcase # => 'I'
. Ruby would have to know not only the character encoding, but also the language to do that correctly.
更糟糕的是,在德语中
'MASSE'.downcase
是要么
'maße' # "measurements"
'masse' # "mass"
换句话说:你需要真正理解文本,即你需要一个成熟的人工智能,才能正确地进行大小写转换.
In other words: you need to actually understand the text, i.e. you need a full-blown AI, to do case conversions correctly.
而且我自己实际上偶然构造了一个句子,即使对于人类来说也是不可判定的.
And I myself have actually accidentally constructed a sentence once, which was undecidable even for a human.
简而言之:完全不可能正确执行,这就是为什么 Ruby 根本不这样做.但是,有第三方库,例如 Unicode 库和 ActiveSupport,它们确实支持更大的字符子集.
In short: it's simply impossible to do correctly, which is why Ruby doesn't do it at all. There are third-party libraries, however, like the Unicode library and ActiveSupport, which do support a somewhat larger subset of characters.
这篇关于如何在 UTF-8 字符上使用 String 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!