LoginSignup
27
29

More than 5 years have passed since last update.

異なるエンコーディングでのファイル書き出しと読み込み

Last updated at Posted at 2013-01-29

古いシステムのために EUC-JP でファイル書き出しをする必要がある場合,内部エンコーディングは UTF-8 だったので,今まで明示的に書き込む文字列を EUC-JP に変換してから書き込んでいた.
でも,次のようにモードでエンコーディングを指定すると自動でその変換をやってくれるらしい.

# coding: UTF-8

# UTF-8 から EUC-JP へ変換して書き込んでくれる.
File.open("hoge-euc", "w:EUC-JP:UTF-8") do |f|
  f << "ファイルの中身"
end

同様に,ファイルからの読み込みもファイル読み込み時にエンコーディングを指定できる.
encoding キーワードを付ければ良い.

# coding: UTF-8

# EUC-JP のファイルを読み込んで UTF-8 に変換する
puts File.read("hoge-euc", encoding: 'EUC-JP:UTF-8')
27
29
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
27
29