In Java, you can do instanceof
. Is there a Ruby equivalent?
views:
80answers:
4It's almost exactly the same. You can use Object
's instance_of?
method:
"a".instance_of?(String) # => true
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.
Have look at instance_of?
and kind_of?
methods. Here's the doc link http://ruby-doc.org/core/classes/Object.html#M000372
In Ruby, variables aren't objects, therefore they aren't instances of any classes und thus it doesn't make sense to check whether they are instances of any specific class.
Note that the same applies to Java, too: instanceof
does not, as you claim, check if a variable is an instance of a class. It checks whether the object that the variable points to is an instance of a class. That is something completely different.