Windowsでプログラムしていると、
コマンドプロンプトの設定はsjisのままがいいけど、Rubyファイルはutf8で扱いたい。なんてことがよくあると思います。(俺だけ?)
で、その何が問題かと言うと、
「Rubyファイルの文字コードをutf8で保存すると、printやputsで出力したときに日本語が文字化けする」ってことです。
じゃあRubyファイルをsjisにするか、コマンドプロンプトをutf8にしろよっていう声が聞こえてきそうですが、
Rubyファイルはutf8じゃないといろいろと問題があって、コマンドプロンプトは他のsjisのプログラムが実行しにくくなるので嫌です。
ということで、出力するときの文字コードを指定できるメソッドを書いてみました。
#!/usr/bin/ruby
$CCODE = 's'
require 'nkf'
def cputs(s,icode="")
if icode!=""
case icode[0,1].upcase
when 'W' then i=icode
when 'U' then i='W'
when 'I' then i='J'
else i=icode[0,1]
end
else i='' end
if $CCODE!=""
case $CCODE[0,1].downcase
when 'w' then o=$CCODE
when 'u' then o='w'
when 'i' then o='j'
else o=$CCODE[0,1]
end
else puts s;return false end
puts NKF.nkf("-#{o}#{i}xm0", s)
return true
end
def cprint(s,icode="")
if icode!=""
case icode[0,1].upcase
when 'W' then i=icode
when 'U' then i='W'
when 'I' then i='J'
else i=icode[0,1]
end
else i='' end
if $CCODE!=""
case $CCODE[0,1].downcase
when 'w' then o=$CCODE
when 'u' then o='w'
when 'i' then o='j'
else o=$CCODE[0,1]
end
else print(s);return false end
print(NKF.nkf("-#{o}#{i}xm0", s))
return true
end
cputsがputsの文字コード指定版で、cprintがprintの文字コード指定版です。cputs "こんにちわ" cprint "ハロー, 世界。"とすれば文字コードを変換して出力します。
この記事にトラックバックする