Relationship operator for classes

R

Ronald Fischer

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 =3D=3D=3D Hash # =3D> 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 =3D=3D=3D is defined for classes that way - it =
seems to
*always* return false.=20

Ronald
--=20
Ronald Fischer <[email protected]>
Phone: +49-89-452133-162
 
S

Stefano Crocco

Alle gioved=EC 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 =3D=3D=3D Hash # =3D> 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 =3D=3D=3D is defined for classes that way - it seems= to
*always* return false.

Ronald

You need
=20
case v
when Symbol
...
when Hash
...
else
...
end

The reason is that Class#=3D=3D=3D returns true if the argument is an insta=
nce of=20
the class or of its descendents. In other words, it works like=20
Object#instance_of?:

a =3D []
a.instance_of? Array
=3D> true
a.instance_of? Object
=3D> true
a.instance_of? String
=3D> false

Array =3D=3D=3D a
=3D> true
Object =3D=3D=3D a
=3D> true
String =3D=3D=3D a
=3D> false

Notice that you need to be careful if you need to check whether the class =
of=20
an object is *exactly* a given class. If you need to distinguish between a=
=20
class and a descendent, you have to put them in the correct order in the ca=
se=20
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
 
R

Ronald Fischer

You need
=20
case v
when Symbol
...
when Hash
...
else
...
end
=20
The reason is that Class#=3D=3D=3D returns true if the argument is=20
an instance of=20
the class or of its descendents.

Thanks a lot, that was it!!

Ronald
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,965
Messages
2,570,148
Members
46,710
Latest member
FredricRen

Latest Threads

Top