Tim Pease
4/6/2009 11:09:00 PM
On Apr 6, 2009, at 4:12 PM, I=F1aki Baz Castillo wrote:
> Hi, I have this case:
>
> class A ; end
> class B < A ; end
> class C < B ; end
>
> a =3D A.new
> b =3D B.new
> c =3D C.new
>
>
> I look for a way (***) to get the following results:
>
> a)
> a *** A =3D> true
> a *** B =3D> false
> a *** C =3D> false
>
> b)
> b *** A =3D> false (*1)
> b *** B =3D> true
> b *** C =3D> false
>
> c)
> c *** A =3D> false (*2)
> c *** B =3D> true
> c *** C =3D> true
>
>
> Note that I could use =3D=3D=3D, so:
> A =3D=3D=3D a =3D> true
> A =3D=3D=3D b =3D> false
>
> but in cases *1 and *2 the result is not what I want:
>
> A =3D=3D=3D b =3D> true (I want false)
> A =3D=3D=3D c =3D> true (I want false)
>
Well, it's kinda hackish but it does give the correct output. Tailor =20
to suit your needs:
class A
alias :like? :instance_of?
end
class B < A; end
class C < B
def like?( clazz )
return true if clazz =3D=3D B
super
end
end
a =3D A.new
b =3D B.new
c =3D C.new
[A, B, C].each do |clazz|
puts "a.like? #{clazz.name} =3D> #{a.like? clazz}"
end
puts
[A, B, C].each do |clazz|
puts "b.like? #{clazz.name} =3D> #{b.like? clazz}"
end
puts
[A, B, C].each do |clazz|
puts "c.like? #{clazz.name} =3D> #{c.like? clazz}"
end
=3D=3D=3D=3D OUTPUT =3D=3D=3D=3D
a.like? A =3D> true
a.like? B =3D> false
a.like? C =3D> false
b.like? A =3D> false
b.like? B =3D> true
b.like? C =3D> false
c.like? A =3D> false
c.like? B =3D> true
c.like? C =3D> true
Again, I'm not proud of this code -- it works, though, without being =20
too tricky.
Blessings,
TwP=