我有以下文件:
# encoding: UTF-8
a = 1 << 7
puts a.chr.encoding
这让我回到ASCII-8BIT
。为什么这不会给我回复UTF-8
?
答案 0 :(得分:3)
chr
有一个编码参数,默认为US-ASCII,当char为< 0x80
时,默认为< 0xff
的ASCII-8BIT(UTF与ASCII相同):
65.chr.encoding # => #<Encoding:US-ASCII>
128.chr.encoding # => #<Encoding:ASCII-8BIT>
255.chr.encoding # => #<Encoding:ASCII-8BIT>
256.chr.encoding # => RangeError: 256 out of char range
Encoding.default_internal = Encoding::UTF_8
65.chr.encoding # => #<Encoding:US-ASCII>
255.chr.encoding # => #<Encoding:ASCII-8BIT>
256.chr.encoding # => #<Encoding:UTF-8>
65.chr(Encoding::UTF_8).encoding # => #<Encoding:UTF-8>
128.chr(Encoding::UTF_8).encoding # => #<Encoding:UTF-8>
500.chr(Encoding::UTF_8).encoding # => #<Encoding:UTF-8>