In Java, you can do
instanceof. Is there a Ruby equivalent?
It’s almost exactly the same. You can use
"a".instance_of? String # => true "a".instance_of? Object # => false
Ruby also has the
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
is_a? are synonymous. They are Ruby’s equivalent to Java’s
instance_of? is different in that it only returns
true if the object is an instance of that exact class, not a subclass.
Have look at
kind_of? methods. Here’s the doc link http://ruby-doc.org/core/classes/Object.html#M000372
I’ve had success with
klass, which returns the class object. This seems to be Rails-specific.
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.