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."]
未发现编码更改。所以请告诉我正确的方法。
最佳答案
编码 IBM437
和 ASCII
(以及 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 的转换,从而生成带有标签 UTF-8 的 "\xe4\xb8\xad"
。而且这个字符串与我脚本中的其他字符串具有相同的编码,因此我可以轻松使用它。
这很有用,因为当两个 String 操作数具有不同的、不兼容的编码时,许多 String 方法都会失败。例如:
# 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/