LoginSignup
21
12

More than 5 years have passed since last update.

BOM付きCSVを読み込む[Ruby 2.3.0]

Last updated at Posted at 2017-06-19

経緯

おかしいなぁ、data["name"]で取得できないや・・・

test.csv
name,age,comment,type
aoi,29,Idol,male

原因

ExcelでCSV作って、UTF-8にしたは良いが、BOM付きだった。
(nameは一番左のカラムだった)
以下のようにしてやると取得できる。
bom.png

hidden.rb
p data["name"]    #BOMがついてる

解決

CSV.readで以下のように指定して取得する。(foreachで取得できなかった)(追記参照)

csv.rb
csv_data = CSV.read('test.csv', 'r:BOM|UTF-8', headers: true)
csv_data.each do |data|
    p data["name"]
end

追記(6/22)

コメントいただきまして、下記にもありますがCSV.foreachでも取得できました!:thumbsup:

csv.rb
CSV.foreach 'test.csv', {encoding: 'BOM|UTF-8', headers: true} do |data|
    p data["name"] # 取得できる
end

参考

Ruby CSVを扱うためのメモ
ファイルから読み込む時に自動的にBOMを削除する

21
12
5

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
21
12