Shakil Shakil - 5 months ago 10
Ruby Question

Why class comparison in case doesn't work?

In general it is possible to compare two classes like this

x = "String"
puts "A string" if x.class == String


But, when
case
is used like this,

x = "String"
case x.class
when String
puts "A string"
end


It doesn't work. Why?

Update:

In the following case,

x = "String"
case x
when String
puts "A string"
end


it works. Does it mean,
case
converts classes into strings implicitly?

Answer

The comparison is done by comparing the object in the when-clause with the object in the case-clause using the === operator. That operator works as expected with literals, but not with classes. This means that if you want to do a case ... when over an object's class, this will not work.

>> 1 === 1
=> true
>> 1.class === 1.class
=> false