83
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

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

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)}
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
Sign upLogin
83
Help us understand the problem. What are the problem?