LoginSignup
82
83

More than 5 years have passed since last update.

UTF-8からShift_JISに変換する時の注意

Posted at

UTF-8 から SJIS変換する時、

str.encode(Encoding::SJIS, :invalid => :replace, :undef => :replace)

と、やれば Encoding::UndefinedConversionError エラーは出ないのだけど、ハイフン等の情報が失われて"?"になる。

特定の文字を文字コード変換前に変換しておけばOK。
http://esoz.blog.fc2.com/blog-entry-59.html を参考に、Stringを汚さないように書き直しました。

def sjis_safe(str)
  [
    ["301C", "FF5E"], # wave-dash
    ["2212", "FF0D"], # full-width minus
    ["00A2", "FFE0"], # cent as currency
    ["00A3", "FFE1"], # lb(pound) as currency
    ["00AC", "FFE2"], # not in boolean algebra
    ["2014", "2015"], # hyphen
    ["2016", "2225"], # double vertical lines
  ].inject(str) do |s, (before, after)|
    s.gsub(
      before.to_i(16).chr('UTF-8'),
      after.to_i(16).chr('UTF-8'))
  end
end

サンプルは以下。

sjis_safe_test.rb
# coding: utf-8
str = sjis_safe("〜−¢£¬−‖").encode(Encoding::SJIS)
open("out.txt", "w") {|f| f.write(str)}
82
83
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
82
83