gpt4 book ai didi

ruby - 混淆 ARGF#set_encoding

转载 作者:数据小太阳 更新时间:2023-10-29 08:32:46 25 4
gpt4 key购买 nike

ARGF.set_encoding说:

If single argument is specified, strings read from ARGF are tagged with the encoding specified.

If two encoding names separated by a colon are given, e.g. "ascii:utf-8", the read string is converted from the first encoding (external encoding) to the second encoding (internal encoding), then tagged with the second encoding.

所以我尝试了以下方法:

p RUBY_VERSION
p ARGF.external_encoding
ARGF.set_encoding('ascii')
p ARGF.readlines($/)

输出:

D:\Rubyscript\My ruby learning days>ruby true.rb a.txt
"2.0.0"
#<Encoding:IBM437>
["Hi! How are you?\n", "I am doing good,thanks."]

p RUBY_VERSION
p ARGF.external_encoding
ARGF.set_encoding(ARGF.external_encoding,'ascii')
p ARGF.readlines($/)

输出:

D:\Rubyscript\My ruby learning days>ruby true.rb a.txt
"2.0.0"
#<Encoding:IBM437>
["Hi! How are you?\n", "I am doing good,thanks."]

未发现编码更改。所以请告诉我正确的方法。

最佳答案

编码 IBM437ASCII(和 UTF-8)对于 ASCII 字符具有相同的字节序列。所以你不会看到与 String#inspect 的区别。但是,您可以检查输入字符串的 String#encoding 值。

p RUBY_VERSION
p ARGF.external_encoding
ARGF.set_encoding(ARGF.external_encoding,'ascii')
p ARGF.readlines($/).map{|s| s.encoding}

在 Ruby(1.9 及更高版本)中,String 是用某种编码标记的字节序列。您可以从 String#encoding 获取编码。

所以中文单词“中”可以有不同的表示方式:

e4 b8 ad          # tagged with encoding UTF-8
d6 d0 # tagged with encoding GBK
2d 4e # tagged with encoding UTF-16le

我将始终使用 UTF-8 编写我的脚本,也就是说,我的脚本的内部编码是 UTF-8。有时我想处理用 GBK 编码的文本文件(例如名为“a.txt”,内容为“中”)。然后我可以为 IO 对象设置外部编码和内部编码,Ruby 会为我进行转换。

ARGF.set_encoding('GBK', 'UTF-8')
str = ARGF.readline
puts str.encoding

# run $ script.rb a.txt

Ruby 从“a.txt”中读取"\xd6\xd0" 并且由于我已将外部编码指定为 GBK,因此它使用编码 GBK 标记数据。我已将内部编码指定为 UTF-8,因此 Ruby 将 GBK 字节序列转换为 UTF-8,这导致 "\xe4\xb8\xad" 带有 UTF-8 标签。而且这个字符串与我脚本中的其他字符串具有相同的编码,所以我可以轻松使用它。

这很有用,因为当两个字符串操作数具有不同的、不兼容的编码时,很多字符串方法都会失败。例如:

# encoding: utf-8
a = "中" # tagged with UTF-8
b = "中".encode('gbk') # tagged with GBK
puts a + b
#=> Encoding::CompatibilityError: incompatible character encodings: UTF-8 and GBK

关于ruby - 混淆 ARGF#set_encoding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15666458/

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