From: matz@... (Yukihiro Matsumoto) Date: 1996-11-30T02:11:24+09:00 Subject: [ruby-list:1148] Re: Japanese and tr まつもと ゆきひろです In message "[ruby-list:1143] Re: Japanese and tr" on 96/11/29, WATANABE Hirofumi writes: | |渡辺@ソニーです. | |jcode.pl からぱくりました. 叩いてください. たぶん EUC と |SJIS なら動くと思います. こんな感じにしてみました.この線でjcode.rbをruby化するのはど うでしょう.ただ,この場合$KCODEを操作しているのでthreadと相 性が悪そうですね.大域変数を使わずに文字コードを設定できる方 法を考えましょう. -- jtr.rb printf STDERR, "feel free for some warinings:\n" if $VERBOSE class String def _expand1(str) str.gsub!(/\\(.)/, '\1') s, e = str.unpack('CxC') if s <= e str = '' for i in s .. e str += [i].pack('C'); end end str end def _expand2(str) s1, s2, e1, e2 = str.unpack('CCxCC'); if s1 == e1 && s2 <= e2 str = '' for i in s2 .. e2 str += [s1, i].pack('CC'); end end str end private :_expand1, :_expand2 def jtr(from, to) table = {} oldkcode = $KCODE $KCODE = 'n' ascii = "[\000-\177]" kanji = "[\200-\377][\000-\377]-[\200-\377][\000-\377]" pattern1 = /#{ascii + '-' + ascii}/ pattern2 = /#{kanji}/ from.gsub!(pattern2) {_expand2($&)} to.gsub!(pattern2) {_expand2($&)} from.gsub!(pattern1) {_expand1($&)} to.gsub!(pattern1) {_expand1($&)} $KCODE = oldkcode ato = to.split(//) afrom = from.split(//) ato.fill(ato[ato.size-1], ato.size .. afrom.size) if ato.size < afrom.size for i in 0 .. ato.size - 1 table[afrom[i]] = ato[i] end self.split(//).collect{ |c| if table[c] table[c] else c end }.join("") end end # print '[RUBY-LIST:1105]'.jtr('A-ZA-Z0-9', 'a-zA-Z0-9'), "\n";