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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11664403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:19:35  来源:igfitidea点击:

Does Ruby provide a way to do File.read() with specified encoding?

rubyfileencoding

提问by Chthonic Project

In ruby 1.9.x, we can specify the encoding with File.open('filename','r:iso-8859-1'). I often prefer to use a one-line File.read() if I am reading many short files into strings directly. Is there a way I can specify the encoding directly, or do I have to resort to one of the following?

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

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

or

或者

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

回答by mu is too short

From the fine manual:

来自精美手册

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

Opens the file, optionally seeks to the given offset, then returns lengthbytes (defaulting to the rest of the file). readensures the file is closed before returning.

If the last argument is a hash, it specifies option for internal open().

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

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

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

So you can say things like this:

所以你可以这样说:

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