From: nobu.nakada@... Date: 2002-03-15T14:06:15+09:00 Subject: [ruby-dev:16406] Re: ライブラリ拡大計画 なかだです。 At Fri, 15 Mar 2002 05:23:54 +0900, Tanaka Akira wrote: > > > iconvはすぐにでも入れましょう。中田さんのですね。 > > > お願いしてもよい? > > > > 入れました。 > > ドキュメントを読んでみました。 > > Iconv.open(to, from) > > Equivalents to Iconv.new except with in the case of called with a block, > yields with the new instance and closes it, and returns the result which > returned from the block. > > という記述からは Iconv.new はブロックをとれないように思うし、実際そう > 動作するのですが、 > > Iconv.new(to, from) {|cd| (strs + nil).collect {|s| cd.iconv(s)}} > > とか、 > > Iconv.new(to, from) do |cd| > input.each {|s| output << cd.iconv(s)} > output << cd.iconv(nil) > end > > という例ではいきなりブロックを指定しています。 > 指定できるのとできないのとどっちを意図しているんでしょう? ドキュメントが古いです。これはFile.newがブロックを使わなくなっ たのに合わせて変更したんですが、ドキュメントを直し忘れてました。 > ついでにいうと、前者の例の + nil というのもよくわからないです。 これは、シフトステートを初期状態に戻すシークェンスを追加するた めです。iconvは内部でシフト状態を保持するので、ISO-2022-JPなど のステートフルなエンコーディングでも、nkfとは違って全部一度に変 換する必要はないのですが、逆に文字列の終りでは明示的にシフト状 態を戻してやる必要があります。 Iconv#iconv(str, [ start = 0, [ length = -1 ] ]) Converts string and returns converted one. □ In the case of str is String, converts str[start, length]. Returns converted string. □ In the case of str is nil, places converter itself into initial shift state and just returns a string contains the byte sequence to change the output buffer to its initial shift state. □ Otherwise, causes exception. さもないと、たとえば日本語の文字列をISO-2022-JPに変換した場合、 単純にASCII文字列を追加したりそのまま出力したりするとかなり意外 な結果になります。 Iconv.open("ISO-2022-JP", "EUC-JP") {|cd| cd.iconv("\xa1\xa1")} # => "\e$B!!" Iconv.conv("ISO-2022-JP", "EUC-JP", "\xa1\xa1") # => "\e$B!!\e(B" -- --- 僕の前にBugはない。 --- 僕の後ろにBugはできる。 中田 伸悦