49

最近 Unicode BOM ヘッダー (U+FEFF) が追加されたデータ フィードを使用していますが、rake タスクが混乱しています。

最初の 3 バイトをスキップできfile.gets[3..-1]ますが、BOM が存在するかどうかにかかわらず、これを正しく処理できる Ruby でファイルを読み取るよりエレガントな方法はありますか?

4

3 に答える 3

78

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')

BOMがファイルで使用可能かどうかは関係ありません。


他のコマンドでエンコードオプションを使用することもできます。

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 }
}
于 2011-10-15T20:48:43.207 に答える