How to check if a variable is an instance of a class?

In Java you can do instanceof . Is there an equivalent to Ruby?

+50
inheritance ruby introspection
Aug 6 '10 at 2:35 a.m.
source share
4 answers

It is almost the same. Can you use the Object instance_of? method instance_of? :

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

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

 "a".is_a? String # => true "a".is_a? Object # => true 
+100
Aug 6 '10 at 14:38
source share

kind_of? and is_a? are synonyms. They are equivalent to Ruby for Java instanceof .

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

+7
May 09 '14 at 10:09
source share

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

+6
Aug 6 2018-10-06
source share

I had success with klass , which returns a class object. This is similar to 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 does this: Object.is_a? , which takes a class object as an argument and returns true if self is an instance of a class or an instance of a subclass.

+4
Aug 6 '10 at 14:40
source share



All Articles