From: shugo@... (Shugo Maeda) Date: 1997-11-27T01:23:34+09:00 Subject: [ruby-dev:928] Re: extension of case 前田です。 In message "[ruby-dev:876] Re: extension of case" Shugo Maeda wrote: |class Limit | def initialize(limit, message) | @limit = limit | @message = message | end | | def Limit.<(limit) | new(limit, :<) | end (snip) | def ===(n) | return n.send(@message, @limit) | end |end ふと思いついたのですが,method_missingを使って class Condition def initialize(msg, arg) @msg = msg @arg = arg end def Condition.method_missing(msg, arg) new(msg, arg) end def ===(obj) return obj.send(@msg, @arg) end end とすれば, case n when Condition == 0 when Condition > 0 ... when Condition < 0 ... end のような演算子だけでなく, array = [ ... ] case array when Condition.include?("foo") ... when Condition.include?("bar") ... end みたいに任意のメソッドを使えますね。 Limitは半分冗談でしたが,Conditionは結構使えるかも。 # 毎回インスタンスを作るのでループ内で使ったりすると # 痛い目に合いそうですが。 しかし,14行で書けるところが,ruby恐るべしというか(^^; -- 前田 修吾