Use is_a?: value.is_a?(String) returns true when value is a String or a subclass of it (kind_of? is the same method). instance_of? accepts only the exact class. To see what something is, call value.class, and when any object with the right method will do, ask value.respond_to?(:each) instead.
Ruby has no typeof and no type annotations to lean on: every value is an object, and you ask the object about its class. The sections below cover is_a? next to instance_of? and .class ==, finding a type with .class and .ancestors, branching on types with case/when and pattern matching, checking for a boolean when Ruby has no Boolean class, duck typing with respond_to?, and comparing two classes with <, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1is_a? and kind_of? vs instance_of?Recommended
obj.is_a?(Klass) is true when Klass is anywhere in the object's ancestry: its own class, a superclass, or a module mixed in with include. kind_of? is another name for the same method. instance_of? is stricter and only matches the exact class, which makes it the same test as obj.class == Klass. Almost always you want is_a?: code that checks for Animal should accept a Dog, and an Integer should count as Numeric. The same call answers the everyday questions: is it a string, is it an array, is it either a hash or an array.
module Walkable; end class Animal; end class Dog < Animal include Walkable end rex = Dog.new # is_a? (alias kind_of?) follows the whole ancestry p rex.is_a?(Dog) p rex.is_a?(Animal) p rex.kind_of?(Walkable) p rex.is_a?(String) # instance_of? and .class == accept only the exact class p rex.instance_of?(Dog) p rex.instance_of?(Animal) p rex.class == Animal # Built-in classes work the same way p 5.is_a?(Integer) p 5.is_a?(Numeric) p 5.is_a?(Comparable) p 5.instance_of?(Numeric) # A String? An Array? A Hash or an Array? value = [4, 2] p "42".is_a?(String) p value.is_a?(Array) p value.is_a?(Array) || value.is_a?(Hash) p [Array, Hash].any? { |klass| { n: 42 }.is_a?(klass) }
Output
rex is a Dog, an Animal and a Walkable for is_a?, but instance_of?(Animal) and rex.class == Animal both print false. The same split shows with numbers: 5.is_a?(Numeric) is true (and so is Comparable, a module), while 5.instance_of?(Numeric) is false. is_a? takes exactly one class; passing two raises ArgumentError: wrong number of arguments (given 2, expected 1), so test several with || or any? as in the last lines, or with case (section 3).
2Find out the type: .class, .name and .ancestors
To find out what an object is, rather than test for one class, call .class. It is Ruby's answer to Python's type(x) and JavaScript's typeof, and it returns the class object itself, not a string; call .name when you need the name as a String. superclass goes one step up, and ancestors lists every class and module that is_a? would accept, in the order Ruby looks up methods.
values = [42, 1.5, "hi", :ok, [1], { a: 1 }, 1..2, nil, true] values.each { |v| puts "#{v.inspect.ljust(7)} #{v.class}" } # .class returns the class itself; .name gives a String p 42.class p 42.class.name puts "Type: #{42.class}" # Classes are objects too p Integer.class p Comparable.class module Walkable; end class Animal; end class Dog < Animal include Walkable end # superclass is one step up; ancestors is the whole chain p Dog.superclass p Dog.ancestors p Integer.ancestors
Output
Even nil and true have classes: NilClass and TrueClass. p 42.class prints Integer while p 42.class.name prints "Integer" with quotes, which shows the second one is a string. The chain for Dog is [Dog, Walkable, Animal, Object, Kernel, BasicObject]: the module sits right after the class that includes it, so Dog.ancestors.include?(Walkable) is another way to ask the is_a? question about a class. Use .class for logging and debugging; for decisions, is_a? is shorter and handles subclasses.
3Branch on the type: case/when and pattern matching
When the answer decides between several paths, put the classes in a case statement. when Integer calls Integer === value, and for a class === means is_a?, so subclasses match and one when can list several classes (more in how to use a case statement). Pattern matching with in (Ruby 3) checks classes the same way, joins alternatives with |, and can bind the value as it checks it, which is handy for arrays and hashes from JSON.
def describe(value) case value when Integer, Float then "a number: #{value}" when String then "a string of #{value.size} chars" when Array, Hash then "a collection of #{value.size}" when nil then "nil" else "a #{value.class}" end end [7, 2.5, "hello", [1, 2], { a: 1 }, nil, :ok].each do |v| puts describe(v) end # when calls ===, and Class#=== is is_a? p Integer === 7 p Numeric === 2.5 p 7 === Integer # Pattern matching: in with one class or several x = 2.5 ok = (x in Integer | Float) p ok puts "not an Integer" unless x in Integer # Without the parentheses, ok = x runs first wrong = x in Integer | Float p wrong # Check the types and bind the values in one step case ["Ann", 31] in [String => name, Integer => age] puts "#{name} is #{age}" end config = { port: "8080" } case config in { port: Integer => port } puts "port #{port}" in { port: String => port } puts "port given as a string: #{port.inspect}" end
Output
2.5 lands in the first when next to 7, and :ok falls through to else, which prints its class. Order matters: Integer === 7 is true but 7 === Integer is false, because === belongs to the left side. The pattern lines print true and not an Integer. Then the trap: wrong = x in Integer | Float prints 2.5, because Ruby runs wrong = x first and matches the result, so wrap the match in parentheses when you store it (or pass it to p). In the hash pattern, "8080" fails the Integer branch and matches the String one.
4Check for a boolean (there is no Boolean class)
Ruby has no Boolean class to pass to is_a?: true is the only instance of TrueClass and false the only instance of FalseClass, and the two classes share no parent of their own. So test for the two values: [true, false].include?(flag), the pattern flag in true | false, or when true, false in a case. Don't confuse this with truthiness: !!value turns anything into true or false but says nothing about what the value was.
# Ruby has no Boolean class p true.class p false.class p defined?(Boolean) # So test for the two values themselves [true, false, nil, 0, "true"].each do |v| puts "#{v.inspect.ljust(6)} boolean? #{[true, false].include?(v)}" end flag = false p((flag in true | false)) p flag == true || flag == false case flag when true, false then puts "a boolean" else puts "not a boolean" end # !! converts any value to a boolean; it does not test for one p !!"yes" p !!nil begin true.is_a?(Boolean) rescue NameError => e puts "#{e.class}: #{e.message}" end
Output
true.class is TrueClass, false.class is FalseClass, and defined?(Boolean) prints nil, so true.is_a?(Boolean) fails with NameError: uninitialized constant Boolean. In the loop only true and false pass; nil, 0 and the string "true" do not. Python readers: 0 is not a boolean in Ruby and is truthy, which is why !! is the wrong check. Testing for nil is simpler: value.nil?.
5Duck typing: respond_to? and method_defined?
Idiomatic Ruby often skips the class check and asks whether the object can do what you need: if it responds to speak, call speak. obj.respond_to?(:name) answers that for an object, so code written this way accepts any class with the method, including ones you never planned for. To ask the class instead, without an instance, use Klass.method_defined?(:name). Both ignore private methods unless you ask for them.
class Duck def speak = "Quack" private def secret = "hidden" end class Robot def speak = "Beep" end # Ask whether the object can do it, not what it is [Duck.new, Robot.new, 42].each do |thing| if thing.respond_to?(:speak) puts thing.speak else puts "#{thing.class} can't speak" end end # Private methods need the second argument duck = Duck.new p duck.respond_to?(:secret) p duck.respond_to?(:secret, true) # From the class, without an instance p Duck.method_defined?(:speak) p Duck.method_defined?(:secret) p Duck.private_method_defined?(:secret) p Duck.instance_methods(false) # Anything that can sum, not only arrays def total(items) items.respond_to?(:sum) ? items.sum : items end p total([1, 2, 3]) p total(1..4) p total(10)
Output
Duck and Robot share no parent class, yet both print, and 42 is skipped with Integer can't speak. respond_to?(:secret) is false for the private method and true once you pass true as the second argument; on the class side, method_defined? skips it and private_method_defined? finds it. instance_methods(false) lists only the methods the class defines itself: [:speak]. total sums an array (6) and a range (10) the same way and returns 10 unchanged for a plain number. The same idea covers strings that hold numbers: their class is String either way, so ask for a conversion with Integer("42", exception: false), which returns 42, or nil for "4x2".
6Compare two classes: <, <= and ancestors
When you hold a class rather than an instance, is_a? is the wrong tool (Dog.is_a?(Animal) asks whether the class object is an animal). Compare the classes with <: Dog < Animal is true when Dog inherits from Animal or includes it as a module. <= also accepts the class itself, and ancestors.include? spells the same test out. The catch is the third answer: for two unrelated classes the result is nil, not false.
module Walkable; end class Animal; end class Dog < Animal include Walkable end class Puppy < Dog; end # < means "is a subclass of" p Dog < Animal p Dog < Dog p Dog <= Dog p Animal < Dog p Dog < String # Modules count too p Dog < Walkable p Dog.include?(Walkable) p Puppy.ancestors.include?(Animal) # Walk the chain up and down p Puppy.superclass p Puppy.superclass.superclass p Animal.subclasses # Built-in classes p Integer < Numeric p Float < Integer # From an instance p Puppy.new.class < Animal
Output
Dog < Dog is false and Dog <= Dog is true; Animal < Dog is false because the relation goes the other way, while Dog < String and Float < Integer print nil because the classes are not related at all. Both are falsy, so an if treats them alike, but don't compare the result with == false. Puppy counts as an Animal two levels up, and Animal.subclasses lists only the direct children, [Dog]. The last line turns an instance question into a class one, though Puppy.new.is_a?(Animal) is the simpler way to write it.
7Which should you use?
| Method | Subclasses match | Returns | Best for |
|---|---|---|---|
| x.is_a?(Foo) | Yes, and modules | true / false | Most type checks |
| x.kind_of?(Foo) | Yes, and modules | true / false | Same method as is_a? |
| x.instance_of?(Foo) | No: exact class | true / false | When a subclass must not pass |
| x.class == Foo | No: exact class | true / false | Avoid: instance_of? says it better |
| case x when Foo | Yes (Foo === x) | The branch taken | Several types, one branch each |
| x in Foo | Bar | Yes (uses ===) | true / false | Checking and destructuring data |
| x.respond_to?(:m) | Any class with m | true / false | Duck typing: can it do this? |
| Sub < Base | Yes, and modules | true / false / nil | Comparing two classes |
Frequently asked questions
What is the difference between is_a?, kind_of? and instance_of? in Ruby?
is_a? and kind_of? are the same method: true when the class you pass is the object's class, a superclass or an included module. instance_of? is true only for the exact class. For a Dog < Animal, dog.is_a?(Animal) is true and dog.instance_of?(Animal) is false.
What is the Ruby equivalent of typeof or type()?
value.class, which returns the class object (42.class is Integer, nil.class is NilClass). Use value.class.name for the name as a string, and value.class.ancestors for every class and module it counts as.
Is there a Boolean type in Ruby?
No. true is a TrueClass and false is a FalseClass, and true.is_a?(Boolean) raises NameError: uninitialized constant Boolean. Check for the two values instead: [true, false].include?(x), or x in true | false inside an if or in parentheses.
How do I check if a variable is a string in Ruby?
value.is_a?(String). A symbol such as :name is not a string, so it returns false for one. If you want to accept anything that behaves as a string, value.respond_to?(:to_str) is the duck-typed check: true for strings, false for symbols and numbers.
How do I check if a string holds a number?
Its class is still String, so ask for a conversion instead: Integer("42", exception: false) returns 42 and Integer("4x2", exception: false) returns nil; Float() works the same way. Without exception: false, Integer("abc") raises ArgumentError: invalid value for Integer(): "abc". Avoid to_i for this: "4x2".to_i quietly returns 4.
Can is_a? check several classes at once?
No, it takes one class; x.is_a?(Integer, Float) raises ArgumentError: wrong number of arguments (given 2, expected 1). Write x.is_a?(Integer) || x.is_a?(Float), check a shared parent such as Numeric, use [Integer, Float].any? { |k| x.is_a?(k) }, or a case with when Integer, Float.