DEV Community

Alexander Spitsyn
Alexander Spitsyn

Posted on • Originally published at jetrockets.pro

Determining class of an object with case equality operator (===)

Case equality operator (or triple equals, ===) in Ruby returns true if the passed class is in the ancestors list of the passed object's class:

1.class.ancestors # [Integer, Numeric, Object, ...]
Numeric === 1 # true
Object === 1 # true

So it can be used for determining object's class:

String === 'abc' # true
'abc'.class #=> String

In cases above the case equality operator works like #kind_of? (or #is_a?):

1.kind_of?(Integer) # true
1.is_a?(Numeric) # true

The classes above has different implementations of === operator, that's why the results of comparison are different:

String.===('abc') # the same as String === 'abc'

Also it means that order of the arguments is important:

1 === Integer # false

Top comments (1)

Collapse
 
baweaver profile image
Brandon Weaver

Be careful of accidentally using strict equality with === like so:

String === 's'.class

That works with == but will fail with ===.

=== is all types of fun in Ruby, especially for case statements and predicate methods like any?. It's even more fun when you realize Proc uses === for call. Taken one step further you can make your own classes which respond to === to do fun things.