From: keiju@... (Keiju ISHITSUKA) Date: 1998-03-18T14:00:44+09:00 Subject: [ruby-list:7155] undefined class switch けいじゅ@日本ラショナルソフトウェアです. サブジェクトがわけ分からんですが(^^;;; 未定義変数(クラス)を含む可能性 のあるswitchをエレガントに書く方法を教えて下さい. Bigfloatの件なんですが, 以下のようにタイプスイッチを行なっています. def /(other) case other when Bigfloat #break when Integer, Rational self / Bigfloat(other) when Float Float(self) / other when Complex Complex(self) / other else x, y = other.coerce(self) x / y end ... ここで問題になるのが, このままだと, 本来必要のないComplexやRationalを requireしないといけなくなります. で, requireしなくとも動作するようにし たいのですが... 今思いつく幾つかの方法をあげますと: 1. ifを使う. def /(other) case other when Bigfloat #break when Integer self / Bigfloat(other) when Float Float(self) / other else if defined?(Complex) and Complex === other Complex(self) / other elsif defined?(Rational) and Rational === other self / Bigfloat(other) else x, y = other.coerce(self) x / y end end と ifでその中で分岐するか... # 全部ifでも良いですが... とにかくあまりエレガントではないですよね... 2. クラスをダミーで定義する. class Rational < Numeric; end class Complex < Numeric; end def /(other) case other when Bigfloat #break when Integer, Rational self / Bigfloat(other) when Float Float(self) / other when Complex Complex(self) / other else x, y = other.coerce(self) x / y end ... このようにとりあえずクラスを定義しちゃうか... これも, ダミーでクラスを作っちゃうのが気になりますよね... さらに, スー パクラスを指定しないで: class Rational; end class Complex; end こんな感じならまだ良いのですが... スーパクラスを指定しないといけないの が, すっごく気になります. 3. 完全ではないのですが, def /(other) case other when Bigfloat #break when Integer, defined?(Rational) and Rational self / Bigfloat(other) when Float Float(self) / other when defined?(Complex) and Complex Complex(self) / other else x, y = other.coerce(self) x / y end というのもありますが, otherがfalseの時に変なところでマッチしてしまいま すので... 完全にするには, 以下のようなコードが必要になります. def /(other) case other when false .... when Bigfloat #break when Integer, defined?(Rational) and Rational self / Bigfloat(other) when Float Float(self) / other when defined?(Complex) and Complex Complex(self) / other else x, y = other.coerce(self) x / y end やはりfalseの辺りが間接的で気分が良くないですねえ... なんかもうちょっとエレガントな方法がありませんかねえ... __ ..............................石塚 圭樹@日本ラショナルソフトウェア... ----------------------------------->> e-mail: keiju@rational.com <<---