我正在使用一个最近添加了Unicode BOM头(U+FEFF)的数据源,我的rake任务现在被它搞砸了.
我可以用file.gets[3..-1]
跳过前3个字节,但是有没有一种更优雅的方法来读取Ruby中的文件,无论是否存在BOM表,都可以正确处理这个问题?
我正在使用一个最近添加了Unicode BOM头(U+FEFF)的数据源,我的rake任务现在被它搞砸了.
我可以用file.gets[3..-1]
跳过前3个字节,但是有没有一种更优雅的方法来读取Ruby中的文件,无论是否存在BOM表,都可以正确处理这个问题?
使用ruby 1.9.2,您可以使用模式r:bom|utf-8
text_without_bom = nil #define the variable outside the block to keep the data
File.open('file.txt', "r:bom|utf-8"){|file|
text_without_bom = file.read
}
或
text_without_bom = File.read('file.txt', encoding: 'bom|utf-8')
或
text_without_bom = File.read('file.txt', mode: 'r:bom|utf-8')
It doesn't matter, if the BOM is available in the file 或 not.
您还可以将"编码"选项与其他命令一起使用:
text_without_bom = File.readlines(@filename, "r:utf-8")
(得到一个包含所有行的数组).
或使用CSV:
require 'csv'
CSV.open(@filename, 'r:bom|utf-8'){|csv|
csv.each{ |row| p row }
}