LoginSignup
1
0

More than 5 years have passed since last update.

SmarterCSVで文字コードを指定して読み込む方法

Last updated at Posted at 2019-03-13

RubyのハッシュにCSVファイルを読み込むとき、SmarterCSVを利用すると1行で書けてとても便利です。

ただし、デフォルトではUTF-8としてファイルが読み込まれます。
しかし、Windowsで作成されたCSVだとエンコーディングが'cp932'1になっていることもありますので、明示的にcp932を指定して読み込む必要があります。2

その指定方法を調べるのに10分ほどかかってしまったので、メモしておきます。

code
require 'smarter_csv'

csv_hash = SmarterCSV.process(filepath, {file_encoding: 'cp932'})

参考

https://www.rubydoc.info/github/tilo/smarter_csv
https://stackoverflow.com/questions/30085334/smartercsv-and-file-encoding-issues-in-ruby


  1. いわゆるShift_JIS。MS独自の拡張が入っているので、厳密にはcp932とかWindows-31Jと呼ばれます。 

  2. 歴史的経緯もありますが、そろそろUTF-8に統一してほしいものです。。。 

1
0
0

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
1
0