How to Get the Class Name of a Ruby Object?

To get the name of an object's class in Ruby, you can simply use object.class.name, for example, like so:

print [].class.name #=> Array
print "".class.name #=> String
# ...

If your class is a part of a module, then the output for object.class.name would also include the module name. For example:

module Shape
  class Triangle
  end
end

triangle = Shape::Triangle.new

print triangle.class.name #=> Shape::Triangle

To only get the class name, you can remove the module name, for example, like so:

print triangle.class.name.split("::").last #=> Triangle

If you're using Rails, then you may use the demodulize method to achieve the same:

print triangle.class.name.demodulize #=> Triangle

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.