UTF-8是Ruby v.2中的默认编码吗?
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 => # '×'.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,那么请将新添加的function检查到较新版本的Ruby。 它并不是那么多。