Newbie question: behaviour of String === String

Hello!

While learning Ruby I stumbled across something I don’t understand:

Object === Object
=> true

String === String
=> false

Can anyone tell me, why Ruby behaves this way? I came across this when I
tried to understand, why this works:

case 'abc’
when String
’a String’
else
’not a String’
end
=> “a String”

… but this doesn’t work the way I expected it to:

case ‘abc’.type
when String
’a String’
else
’not a String’
end
=> “not a String”

thanks

Bernhard Weitzhofer

Bernhard,

While learning Ruby I stumbled across something I don’t understand:

Object === Object
=> true

String === String
=> false

Can anyone tell me, why Ruby behaves this way?

Module#=== (which is what you are calling in both examples) returns true

if the parameter (the one on the right-hand side of the ===) is an instance
of the module (on the left-hand side) or one of its descendants. Since the
class String is not an instance of the class string, this is false. The
reason that the first example is true is because virtually everything in
Ruby is an instance of class Object.

Some more examples may help illustrate:

irb(main):001:0> Object === Object
=> true
irb(main):002:0> Object === Class
=> true
irb(main):003:0> Object === ‘str’
=> true
irb(main):004:0> Object === 1.5
=> true
irb(main):005:0> Object === :symbol
=> true
irb(main):006:0> String === 1.5
=> false
irb(main):007:0> String === ‘1.5’
=> true

Don't confuse this with operator '=='.  Operator '===' is used almost

exclusively for case statements and its behavior is tied pretty closely with
them.

I hope this helps!

- Warren Brown

In order to get the behavior you want, you could try this:

case obj.class.id
when String.id
’is a String’
when Integer.id
’is an Integer’
else
’is something else’
end

Chris