On Mon, Apr 6, 2009 at 11:12 PM, Iñaki Baz C. [email protected] wrote:
b *** C => 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