Ruby是否提供了使用指定编码执行File.read()的方法?

问题描述 投票:33回答:1

在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个回答
54
投票

来自fine manual

read(name,[length [,offset]],open_args)→string

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

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

所以你可以这样说:

>> s = File.read('pancakes', :encoding => 'iso-8859-1')
>> s.encoding
=> #<Encoding:ISO-8859-1>
© www.soinside.com 2019 - 2024. All rights reserved.