我希望我的脚本能够从标准输入获取数据,这些数据可能以UTF8或UTF16编码提供。例如:
数据来源 | my-script -e utf8
我该如何设置stdin的外部编码?ruby
解释器时,您可以添加--encoding utf-8
参数以指定stdin编码。
#!/usr/bin/env ruby --encoding utf-8
text = ARGF.read
man ruby
:
-E external[:internal]
--encoding external[:internal]
Specifies the default value(s) for external encodings and
internal encoding. Values should be separated with colon
(:).
You can omit the one for internal encodings, then the
value (Encoding.default_internal) will be nil.
IO.new
文档中有详细说明。该方法中详细的信息适用于其他“读取”类型的方法,例如read
,gets
,foreach
。 - the Tin Man