How to print the name of a Ruby class| Ruby on Rails By Example

Ruby contains classes and objects.

Sometimes, We need to get the name of a class for a given class variable or object.

How to get the name of a Ruby class?

How to find the ruby class name with example

Let’s declare an Employee class

class Employee
   def initialize(id, name, salary)
      @id = id
      @name = name
      @salary = salary
   end
end

Create an object for this class.

emp1 = Employee.new("1", "Ram", 5000)
emp2 = Employee.new("2", "Frank", 4000)

There are multiple ways we can check the name of a class in Ruby.

One way using object.class.name, another way using object.class.to_s. object.class.name returns the class or module name, nil return for anonymous classes.

class Employee
   def initialize(id, name, salary)
      @id = id
      @name = name
      @salary = salary
   end
end
emp1 = Employee.new("1", "Ram", 5000)
emp2 = Employee.new("2", "Frank", 4000)

puts emp1.class.name
puts emp2.class.to_s
puts Employee.name
puts Employee.to_s

Output:

Employee
Employee
Employee
Employee