0

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?

Shakil
  • 1,044
  • 11
  • 17
  • 1
    You are asking whether the `class` of `x` is a `String`. Well, obviously, it isn't, it's a `Class`. In the second example, you are asking whether `x` is a `String`, and that's the case. – Jörg W Mittag Jun 27 '16 at 10:43

1 Answers1

1

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

A good explanation and a small showcase on using the === on Class instances in Ruby is in this answer

Community
  • 1
  • 1
Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
  • Particularly interesting in this regard: `1.class === 1` is `true`. – Stefan Jun 27 '16 at 12:36
  • That's because `===` ist just a method that's been called on an instance and the instance can do whatever it sees fit. So obviously a `Fixnum` class matches its values inside the method `===` – Tomasz Stanczak Jun 27 '16 at 14:14