gpt4 book ai didi

ruby - UTF-8 是 Ruby v.2 中的默认编码吗?

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

Matz 在他的书中写道,为了使用 UTF-8,您必须在脚本的第一行添加编码注释。他给了我们一个例子:

# -*- coding: utf-8 -*-   # Specify Unicode UTF-8 characters

# This is a string literal containing a multibyte multiplication character
s = "2x2=4"

# The string contains 6 bytes which encode 5 characters
s.length # => 5: Characters: '2' 'x' '2' '=' '4'
s.bytesize # => 6: Bytes (hex): 32 c3 97 32 3d 34

当他调用bytesize时,它返回6,因为乘法符号×在ascii集之外,必须用unicode表示两个字节。

我尝试了这个练习,在没有指定编码注释的情况下,它将乘法符号识别为两个字节:

'×'.encoding
=> #<Encoding:UTF-8>
'×'.bytes.to_a.map {|dec| dec.to_s(16) }
=> ["c3", "97"]

所以看起来 utf-8 是默认编码。这是最近添加到 Ruby 2 中的吗?他的示例来自 Ruby 1.9。

最佳答案

是的。 UTF-8 是默认编码这一事实仅从 Ruby 2 开始出现。

如果您知道他的示例来自 Ruby 1.9,请查看新版本 Ruby 的新增功能。没那么多。

关于ruby - UTF-8 是 Ruby v.2 中的默认编码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28390653/

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