fabriciofreitag
fabriciofreitag

Reputation: 2883

Ruby case and === on type comparison

I know that case statements use ===, so:

a = "foo"
=>"foo"

case a
when String
  puts "hi"
end
=> hi

but strangely:

a === String
 => false

I was expecting the last expression to return true, what am I missing?

Thanks!!

Upvotes: 0

Views: 102

Answers (2)

fabriciofreitag
fabriciofreitag

Reputation: 2883

The class has to be on the left hand side:

String === a
=> true 

Upvotes: 1

a131
a131

Reputation: 564

To check that class of the variable is String use the equality operator ==.

> a.class == String
=> true

Case statement uses the === operator which is not equality. It's implementation is different for different types(read the documentation for more information). Its implementation is_a? for the specific case below:

> String === 'foo'
=> true

> String === String
=> false

Upvotes: 1

Related Questions