From: Robert Klemme Date: 2003-08-12T20:43:33+09:00 Subject: Re: using case with classes "Ryan Pavlik" schrieb im Newsbeitrag news:20030811190930.5e03fb72.rpav@users.sf.net... > On Tue, 12 Aug 2003 10:25:04 +0900 > Michael Garriss wrote: > > > Ok, this did not work like I expected (because I know too little about > > Ruby): > > > > def test( obj ) > > case obj.class > > when Array then puts "Array" > > when Hash then puts "Hash" > > when Class then puts "Class" > > else puts "ugh" > > end > > end > > try this: > > def test( obj ) > case obj > when Array then puts "Array" > when Hash then puts "Hash" > when Class then puts "Class" > else puts "ugh" > end > end > > Unfortunately the behavior above is still annoying; in this case you > have an object to work with, but I've run into a number of cases > where I have only a class, and I just have to use a big "if" block. No. class TypeCheck def initialize(cl) @cl = cl end def ===(o) @cl == o end end case Array when TypeCheck.new(Array) puts "Array" when TypeCheck.new(Hash) puts "Hash" else puts "buh!" end # even better, because it creates less instances: def TypeCheck(cl) (@@checks ||= Hash.new {|h,k| h[k] = TypeCheck.new(k)} )[cl] end case Array when TypeCheck(Array) puts "Array" when TypeCheck(Hash) puts "Hash" else puts "buh!" end see also ruby talk 76641 robert