ruby – 相同的字符串但不同的字节代码

我有两个字符串:
a = 'hà nội'
b = 'hà nội'

当我将它们与== b进行比较时,它返回false.

我检查了字节码:

a.bytes = [104,97,204,128,32,110,195,180,163,105]
b.bytes = [104,160,225,187,153,105]

原因是什么?如何修复它以使a == b返回true?

解决方法

这是 Unicode equivalence的问题.

为了比较这些字符串,您需要对它们进行标准化,以便它们对这些类型的字符使用相同的字节序列.

a.unicode_normalize == b.unicode_normalize

unicode_normalize(form =:nfc)[link]

Returns a normalized form of str,using Unicode normalizations NFC,
NFD,NFKC,or NFKD. The normalization form used is determined by form,
which is any of the four values :nfc,:nfd,:nfkc,or :nfkd. The
default is :nfc.

If the string is not in a Unicode Encoding,then an Exception is raised. In this context,‘Unicode Encoding’ means any of UTF-8,UTF-16BE/LE,and UTF-32BE/LE,as well as GB18030,UCS_2BE,and UCS_4BE. Anything else than UTF-8 is implemented by converting to UTF-8,which makes it slower than UTF-8.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...