Ruby 1.9 M17N というか文字コード/encodingの扱い

TCPSocket.open(ip, port)として開いた場合、その後eachで取得できるデータのencodingは、ASCII-8BITになっている。
(IPSocketはIOクラスのサブクラスと同様の入出力ができる、と書いてあり*1、IOではeachはテキスト読み込みメソッドでエンコーディングの影響を受けるとなっている*2ので、上記の表現は適切、、、だと思う。)

今回接続先からは、実際はUTF-8で送られてきているので、encodingを修正してやる必要がある。

それには、data.force_encoding("UTF-8")とすればよい。

http://yugui.jp/articles/850
通常のアプリケーションでは、force_encodingを使う場面はないはずですよ、という内容の記事。例外としてforce_encodingを使っても良いケースについては以下のような記述があり、今回はこれに該当するんじゃないかと思った。

force_encoding is for middleware authors. For example, net/http, rack, rails or PostgreSQL adapter. These kind of libraries must accept byte sequence from an external stream and reinterpret the sequence into a string with an encoding. So they need to use force_encoding. And they have the responsibility to provide a string with a correct encoding to library users. If you need force_encoding in your application, it must be a bug of a middleware.

参考
るびま
Ruby 1.9.1のm17nについてメモ - daily gimite
Ruby 1.9 m17n リファレンス (不完全版) - diary of a madman