1

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?

1
  • 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. Commented Jun 27, 2016 at 10:43

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Particularly interesting in this regard: 1.class === 1 is true.
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 ===

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.