gpt4 book ai didi

ruby - 为什么在 Ruby 中将 7 位 ASCII 字符串文字编码为 UTF-8

转载 作者:数据小太阳 更新时间:2023-10-29 07:29:09 26 4
gpt4 key购买 nike

我正在阅读“The Ruby Programming Language”。本书在3.2.6.1节“Ruby 1.9中的多字节字符”中介绍了Ruby字符串的优化

If a string literal contains only 7-bit ASCII characters, then its encoding method will return ASCII, even if the source encoding is UTF-8

我在 ruby​​ 1.9.1-p431、1.9.2 和 1.9.3-p125 上尝试了以下简单脚本,它们都对 7 位 ASCII 字符使用 UTF-8 编码。

# coding: utf-8
s = 'hello'
p s.encoding
# result is #<Encoding:UTF-8>

我想也许这种行为在 Ruby 1.9 的开发过程中发生了变化。我试图搜索 Ruby 1.9 的变更日志,以及 1.9.1 changelog确认此行为。我还克隆了 Ruby 的 git 存储库,但我找不到提及更改此行为的提交。

更新:

查看 Ruby 的源代码库,我猜这是 2008 年 1 月发布的 Ruby 1.9.0 中的行为。(它无法在 Debian 6 上编译,所以我无法准确确认这一点。)虽然《The Ruby Programming Language》是一本优秀的书,但它最初是在 2008 年出版的。很可能书中的某些描述已经过时了。

另一个过时的描述是关于 Encoding.list 方法的行为。因此,如果您也在阅读本书,请注意过时的描述。

最佳答案

我没有那本书,但是 Programming Ruby 书(镐)的当前 Pdf 版本说明

String literals are always encoded using the encoding of the source file that contains them, regardless of the content of the string

然后给出一个例子,其中"dog"获得了utf-8编码。看起来你的书的版本是错误的。我不知道这是打印版中的勘误表还是 ruby​​ 在打印后发生了变化,我不知道

关于ruby - 为什么在 Ruby 中将 7 位 ASCII 字符串文字编码为 UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10315133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com