diolemo
diolemo

Reputation: 2671

Is this the correct way to test whether an object is an instance of a class?

object.class == String
object.class === String

I initially used the first == and it was working fine but this site talks about just ===.

What is the difference when used in this manner?

Upvotes: 0

Views: 68

Answers (1)

Leo Correa
Leo Correa

Reputation: 19789

Here's yet another way:

a = "foo"
a.is_a?(String)

NOTE

a = "foo"
a.kind_of?(String)

kind_of? and is_a? behave the same way. instance_of? will only return true if is an instance of the class and does not account for subclass.

Example

10.class 
#=> Fixnum
10.is_a?(Integer)
#=> true
10.kind_of?(Integer)
#=> true
10.instance_of?(Integer)
#=> false

Upvotes: 2

Related Questions