From: Chris White Date: 2011-08-15T01:26:51+09:00 Subject: Re: How to use "case" to match class names? (=== not so funny) > Hi, easy example of what I need: > > ------------------- > klass = String > > case klass > when String > puts "I'm String class" > else > puts "I'm nothing..." > end > ------------------- > > It produces "I'm nothing...". I understand why: > > "case" matches the given object using "===", and: > > String === String > => false Correct, because triple equals checks to see if the value is an instance or subclass of a class, not if it's the actual class itself > > while: > > String === "a new string" > => true Which is why this works. One way to potentially get around this is to have an object that simple holds a class and overrides the === operator to make case work properly: class ClassCheck def initialize(klass) @holder = klass end def ===(other) @holder == other end end klass = String case klass when ClassCheck.new(String) puts "String" else puts "Nothing" end You could also modify it to accept a variable number of arguments to check against multiple classes in a single when statement: class ClassCheck def initialize(*klass) @holder = klass end def ===(other) @holder.each { | klass | return true if klass == other } false end end klass = String case klass when ClassCheck.new(Object, Numeric, String) puts "One of these" else puts "Nothing" end This form works with a single class as well. Regards, Chris White http://www.twitter.com/cwgem