- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
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,这导致 "\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/
这个问题已经有答案了: Why is gets throwing an error when arguments are passed to my ruby script? (2 个回答) 已关闭 8
使用 ARGF,我可以创建尊重管道的 Ruby 程序。假设,我要不断阅读新条目: $ tail -f log/test.log | my_prog 我可以使用: ARGF.each_line do |
ARGF.set_encoding说: If single argument is specified, strings read from ARGF are tagged with the enco
ARGF.each_with_index do |line, idx| print( "[#{idx}] #{line} x: " ); indent = Indent
我试图让我的代码能够接受来自命令行输入的多个日志文件,以根据不同的分隔符进行解析,并接受命令来解析某个日志文件的所有步骤。 它目前一次只能接受一个命令,它解析的日志文件是在代码中确定的,而不是变量@l
在 Ruby 1.9 中,我如何从 ARGF 中读取 CSV? 我尝试了以下方法,但没有打印任何内容: require 'csv' CSV(ARGF).read do |row| p row
我想像这样处理ARGF。 # file.rb if ARGF.??? puts ARGF.read else puts "no redirect." end $ echo "Hello wor
在 Ruby 1.8.7 中,the documentation不在类和模块下列出 ARGF,并且 ARGF 不是类或模块: ARGF.class # => Object 在 Ruby 1.9.3 中
我使用 GLI 2.0 gem 创建了自己的 gem对于所有漂亮的命令行结构。它工作正常,但我还想支持管道输入的数据。 my_prog new some_file # this is ok alrea
我是一名优秀的程序员,十分优秀!