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
Hope you found this post useful. It was published . Please show your love and support by sharing this post.