Rubyで文字のエンコードのまとめメモ
ソース
ruby
# -*- coding: utf-8 -*-
## Ruby 1.9
str = "あいうえおかきくけこ"
sjis = str.encode "SJIS"
p sjis.encoding #=> #<Encoding:Shift_JIS>
p sjis.length #=> 10
p sjis.bytesize #=> 20
euc = str.encode "EUC-JP"
p euc.encoding #<Encoding:EUC-JP>
p euc.length #=> 10
p euc.bytesize #=> 20
utf8 = str.encode "UTF-8"
p utf8.encoding #<Encoding:UTF-8>
p utf8.length #=> 10
p utf8.bytesize #=> 30
## Ruby 1.8
require 'kconv'
str = "あいうえおかきくけこ"
# nkfコマンドの引数と同じ
#
# output input
# SJIS s S
# EUC-JP e E
# UTF8 w W
# JIS(ISO-2022-JP) j J
sjis = NKF.nkf("-s",str)
p sjis.issjis #=> true
euc = NKF.nkf("-e",str)
p euc.iseuc #=> true
utf8 = NKF.nkf("-w",str)
p utf8.isutf8 #=> true
コメントする