From: Stefano Crocco Date: 2007-08-16T20:00:55+09:00 Subject: Re: Relationship operator for classes Alle gioved� 16 agosto 2007, Ronald Fischer ha scritto: > I wanted to distinguish between cases, where a variable > is of type Symbol, or Hash, or something other. My first > attempt failed: > > case v.class > when Symbol > ... > when Hash > ... > else > ... > end > > Even if v was a Hash, processing endet up in the "else" part. > Indeed, a quick check with irb showed: > > Hash === Hash # => false > > I solved my problem by changing my code to > > case v.class.to_s > when 'Symbol' > ... > when 'Hash' > ... > else > ... > end > > But now I wonder why === is defined for classes that way - it seems to > *always* return false. > > Ronald You need case v when Symbol ... when Hash ... else ... end The reason is that Class#=== returns true if the argument is an instance of the class or of its descendents. In other words, it works like Object#instance_of?: a = [] a.instance_of? Array => true a.instance_of? Object => true a.instance_of? String => false Array === a => true Object === a => true String === a => false Notice that you need to be careful if you need to check whether the class of an object is *exactly* a given class. If you need to distinguish between a class and a descendent, you have to put them in the correct order in the case statement: first the derived class, then the base class: class A;end class B < A; end case obj when B ... when A ... end I hope this helps Stefano