2
5

More than 1 year has passed since last update.

Ruby | エンコーディングを指定してBOM付きファイルを作る

Last updated at Posted at 2016-11-29

解決: こうだ!

例: BOM 付き UTF16-LE の CSVファイル の場合。

File.open('example.csv', 'w:UTF-16LE') do |f|
  f.write "\uFEFF"
  f.write "あ\t\t\t\tお"
end

エンコードの確認

linux の file コマンドでエンコードが分かる。

$ file example.csv
example.csv: Little-endian UTF-16 Unicode text, with no line terminators

中身の確認

more で中身を見てみる。

$ more example.csv
<FF><FE>B0      ^@D0    ^@F0    ^@H0    ^@J0

エクセルで確認

image

以下、失敗例

改行を入れてしまった

puts だと二行に分けた時に改行が入ってしまう。

File.open('example.csv', 'w:UTF-16LE') do |f|
  f.puts "\uFEFF"
  f.puts "あ\t\t\t\tお"
end

image

BOM をシングルクォートで囲ってしまった

File.open('example.csv', 'w:UTF-16LE') do |f|
  f.write "\uFEFF"
  f.write "あ\t\t\t\tお"
end

image

BOM の指定間違え

Wikipediaを参考にしてみたが、"\xFF\xFE" って書くとダメっぽい。(まだよく分かっていない)

image


File.open('example.csv', 'w:UTF-16LE') do |f|
  bom = %w(FF FE).map { |e| e.hex.chr }.join # => "\xFF\xFE"
  f.write bomf
  f.write "あ\t\t\t\tお"
end

# => Encoding::UndefinedConversionError: "\xFF" from ASCII-8BIT to UTF-8

コンソールでの確認

cat とか head コマンドだと、中身にもBOMが文字化けして見えてしまい、うまく作れていないと思いこんでいた。
( more / less だといい感じだった )

$ cat example.csv
��B0	D0	F0	H0	J0% 
$ head example.csv
��B0	D0	F0	H0	J0%

備考

  • ここにたどり着くまでけっこう長かった。

環境

  • ruby 2.3.1
  • Max OS X El Capitan

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

2
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5