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

RubyInheritanceIntrospection

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

kind_of? and is_a? are synonymous. They are Ruby's equivalent to Java's instanceof.

instance_of? is different in that it only returns true if the object is an instance of that exact class, not a subclass.

Solution 3 - Ruby

Have look at instance_of? and kind_of? methods. Here's the doc link http://ruby-doc.org/core/classes/Object.html#M000372

Solution 4 - Ruby

I've had success with klass, which returns the class object. This seems to be Rails-specific.

Sample usage:

class Foo
end

Foo.new.klass
# => Foo

Foo.new.klass == Foo
# => true

Foo.new.klass == "Foo"
# => false

There is also a method that accomplishes this: Object.is_a?, which takes the class object as an argument and returns true if self is an instance of the class or an instance of a subclass.

Solution 5 - Ruby

Adding another answer for completeness. Sometimes, particularly during testing, we may not want to access another class by type, so given a Hash:

h = { one: 'Val 1' }

instead of writing:

h.is_a? Hash # true

we can write:

h.class.name == 'Hash' # true

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNullVoxPopuliView Question on Stackoverflow
Solution 1 - RubyJohn TopleyView Answer on Stackoverflow
Solution 2 - Rubyuser3622081View Answer on Stackoverflow
Solution 3 - RubyAnand ShahView Answer on Stackoverflow
Solution 4 - RubyStevenView Answer on Stackoverflow
Solution 5 - RubyVladView Answer on Stackoverflow