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

查看:16
本文介绍了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 字节(默认为文件的其余部分).read 确保文件在返回前关闭.

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天全站免登陆