{

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
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.