How to get the Class of an Object in Ruby

Published: Wednesday, May 18, 2022

Greetings, friends! As you may know, the Ruby programming language is a pure object-oriented language. Practically everything in Ruby is an object. This means we can use the Object#class method to get the name of any object's class.

ruby
Copied! ⭐️
puts 0.class # Integer
puts 3.14.class # Float
puts "".class # String
puts false.class # FalseClass
puts true.class # TrueClass
puts nil.class # NilClass
puts [].class # Array

hash = {foo: 0, bar: 1, baz: 2}
puts hash.class # Hash

class FancyClass
  def saySomethingFancy
    puts "How Quaint"
  end
end

fancyPerson = FancyClass.new
puts fancyPerson.class # FancyClass
tip
You can try out this code by copying and pasting it to run.rb.

Getting the class name of an object is useful for learning the internals of Ruby or a Ruby library. You can also use the Object#class method to help you debug Ruby code. Sometimes, you may need to figure out where a variable's class is defined or what class it belongs to.

Resources