Relationship operator for classes

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

But now I wonder why === is defined for classes that way - it seems to
always return false.

This is just by my own experimenting, but it seems === is for testing
instance variables.

irb(main):001:0> Hash === {}
=> true
irb(main):002:0> Hash === 3
=> false
irb(main):003:0> Hash === Class
=> false
irb(main):004:0> Class === Hash
=> true
irb(main):005:0> Fixnum === 3
=> true
irb(main):006:0> Object === Class
=> true
irb(main):007:0> Class === Object
=> true
irb(main):008:0>

Cheers,
Arlen.

Alle giovedì 16 agosto 2007, Ronald F. ha scritto:

...

when ‘Symbol’
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

The reason is that Class#=== returns true if the argument is
an instance of
the class or of its descendents.

Thanks a lot, that was it!!

Ronald

case v.class
when Symbol
…
when Hash
…
else
…
end

So on second thoughts, try just removing the “.class” from that code and
try again. :slight_smile:

  • Arlen