Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

古いシステムのために 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')
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした