Ruby提供了一种使用指定编码的File.read()方法吗? [英] Does Ruby provide a way to do File.read() with specified encoding?

查看:209
本文介绍了Ruby提供了一种使用指定编码的File.read()方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ruby 1.9.x中,我们可以使用 File.open('filename','r:iso-8859-1')指定编码。我经常喜欢使用一行File.read(),如果我正在读取很多短文件到字符串直接。有没有办法可以直接指定编码,还是要使用以下方法之一?

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?

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


推荐答案

精细手册


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

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

Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file). read ensures the file is closed before returning.

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

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

所以你可以这样说:

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

这篇关于Ruby提供了一种使用指定编码的File.read()方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆