【问题标题】:Does Ruby provide a way to do File.read() with specified encoding?Ruby 是否提供了一种使用指定编码执行 File.read() 的方法?
【发布时间】:2012-07-26 07:27:20
【问题描述】:

在 ruby​​ 1.9.x 中,我们可以使用File.open('filename','r:iso-8859-1') 指定编码。如果我直接将许多短文件读入字符串,我通常更喜欢使用单行 File.read()。有没有办法可以直接指定编码,还是必须求助于以下方法之一?

str = File.read('filename')
str.force_encoding('iso-8859-1')

f = File.open('filename', 'r:iso-8859-1')
s = ''
while (line = f.gets)
    s += line
end
f.close

【问题讨论】:

    标签: ruby file encoding


    【解决方案1】:

    来自fine manual

    read(name, [length [, offset]], open_args) → 字符串

    打开文件,可选择查找给定的offset,然后返回length 字节(默认为文件的其余部分)。 read 确保文件在返回之前关闭。

    如果最后一个参数是一个哈希,它指定内部 open() 的选项。

    所以你可以这样说:

    s = File.read('pancakes', :encoding => 'iso-8859-1')
    s.encoding
    #<Encoding:ISO-8859-1>
    

    【讨论】:

      猜你喜欢
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多