From: Kazuhiro NISHIYAMA Date: 2000-11-15T00:27:25+09:00 Subject: [ruby-dev:11516] Re: Ruby I18N On Fri, 10 Nov 2000 00:20:54 +0900 " たけ \(tk\)" wrote: >  しかし、次のようにやるとうまくいかないはず。String クラスのリテラルの > 引数は、その時点でコンバートしたい。どうやるんでしょうか?。 > > str1 = String::MyString.new( 'abc' ) > >  * initialize でコンバートしてはいけない。new の引数はそのまま取り込 > まれる。new の引数は String::MyString にコンバートすみのものでなければな > らない。結局 str1 = 'abc'.convert_to String::MyString としたほうがよい。 > となるのかな?。でも、ついうっかりやってしまいそうな気がするなぁ。 うまくサンプルを書けませんでしたが、 String#convert_to(s) Precision#prec(c)相当 String::convert_from(s) Numeric::induced_from(num)相当 に対応させるようなモデルはどうでしょうか? 一般的にはMyString::convert_fromのように何か変換用のメソッドを 用意してそこだけで変換すればよさそうな気がします。 # 高速化したければ+とかも定義すればいいだけだし。 class String def convert_to klass return self if self.type == klass return klass.new(self) end end class String class MyString < String def initialize s self.replace MyString.convert_from s self end end def MyString.convert_from(s) s + "("+s.class.name+"->"+self.name+")" end end class String class YourString < String def initialize s self.replace YourString.convert_from s self end end def YourString.convert_from(s) s + "("+s.class.name+"->"+self.name+")" end end str1 = String::MyString.new( 'abc' ) str2 = str1.convert_to String::YourString p str1.type ## String::MyString p str2.type ## String::YourString p str1 ## "abc(String->String::MyString)" p str2 ## "abc(String->String::MyString)(..MyString->..YourString)" --- ZnZ(ゼット エヌ ゼット) 西山和広(Kazuhiro NISHIYAMA) mailto:zn@mbf.nifty.com