From: Sean O'Halpin Date: 2009-04-07T09:38:01+09:00 Subject: Re: class C < B < A On Mon, Apr 6, 2009 at 11:12 PM, Iñaki Baz Castillo wrote: > Hi, I have this case: > >  class A     ; end >  class B < A ; end >  class C < B ; end > >  a = A.new >  b = B.new >  c = C.new > > > I look for a way (***) to get the following results: > > a) >  a *** A => true >  a *** B => false >  a *** C => false > > b) >  b *** A => false  (*1) >  b *** B => true >  b *** C => false > > c) >  c *** A => false  (*2) >  c *** B => true >  c *** C => true > > > Note that I could use ===, so: >  A === a => true >  A === b => false > > but in cases *1 and *2 the result is not what I want: > >  A === b => true (I want false) >  A === c => true (I want false) > > > I could play with a.class.ancestors, but isn't another way? > > Thanks a lot. > You need to specify somewhere the root of the inheritance hierarchy you're interested in. Something like this: class A def like?(klass) if klass == A self.class == A else self.class <= klass end end end More generally, this will do what you want (at least, what I think you want ;) module RootedClassComparison def self.included(other) module_eval { define_method :like? do |klass| if klass == other self.class == other else self.class <= klass end end } end end class A include RootedClassComparison end class B < A end class C < B end class D < C end a = A.new b = B.new c = C.new d = D.new klasses = [A, B, C, D] # test pinched from Tim's example :) klasses.each do |clazz| puts "a.like? #{clazz.name} => #{a.like? clazz}" end puts klasses.each do |clazz| puts "b.like? #{clazz.name} => #{b.like? clazz}" end puts klasses.each do |clazz| puts "c.like? #{clazz.name} => #{c.like? clazz}" end puts klasses.each do |clazz| puts "d.like? #{clazz.name} => #{d.like? clazz}" end Output: a.like? A => true a.like? B => false a.like? C => false a.like? D => false b.like? A => false b.like? B => true b.like? C => false b.like? D => false c.like? A => false c.like? B => true c.like? C => true c.like? D => false d.like? A => false d.like? B => true d.like? C => true d.like? D => true Regards, Sean