Object#instance_of?
obj.instance_of?(klass) -> true or false Returns:
boolean · Updated March 13, 2026 · Core Classes types class object checking
instance_of? is a Kernel method that checks whether an object is an instance of exactly the given class — not its superclasses. Unlike is_a? and kind_of?, it does not consider the inheritance chain.
Syntax
obj.instance_of?(klass)
Parameters
| Parameter | Type | Description |
|---|---|---|
klass | Class | The exact class to check against |
Examples
Exact class matching
"hello".instance_of?(String)
# => true
"hello".instance_of?(Object)
# => false (it's a String, not Object directly)
[1, 2].instance_of?(Array)
# => true
[1, 2].instance_of?(Object)
# => false
The key difference from is_a?
This is where instance_of? differs from is_a?:
num = 42
num.is_a?(Integer) # => true
num.is_a?(Numeric) # => true (Numeric is superclass)
num.is_a?(Object) # => true (Object is root)
num.instance_of?(Integer) # => true
num.instance_of?(Numeric) # => false (it's an Integer, not Numeric)
num.instance_of?(Object) # => false (it's an Integer, not Object)
Practical use case
Use instance_of? when you need strict type checking that ignores inheritance:
class Config
def initialize(data)
# Must be exactly a Hash, not a subclass
unless data.instance_of?(Hash)
raise ArgumentError, "expected Hash, got #{data.class}"
end
@data = data
end
end
When to use instance_of?
- Strict type checking: When you need to reject subclasses
- Security-sensitive code: When object type matters exactly
- API contracts: When a method requires a specific class, not a compatible one
Most of the time, is_a? is more flexible and appropriate since subclasses typically behave the same as their parents.
Errors
Passing a non-Class raises TypeError:
"test".instance_of?("string")
# => TypeError: class or module required
See Also
- Object#is_a? — Checks class and ancestors
- Object#kind_of? — Alias for is_a?