How do I check if a variable is an instance of a class?

NullVoxPopuli picture NullVoxPopuli · Aug 6, 2010 · Viewed 72.2k times · Source

In Java, you can do instanceof. Is there a Ruby equivalent?

Answer

John Topley picture John Topley · Aug 6, 2010

It's almost exactly the same. You can use Object's instance_of? method:

"a".instance_of? String # => true
"a".instance_of? Object # => false

Ruby also has the is_a? and kind_of? methods (these 2 are aliases, and work exactly the same), which returns true is one of the superclasses matches:

"a".is_a? String # => true
"a".is_a? Object # => true