{

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.





Related posts

How to Convert current Unix timestamp epoch to DateTime in Ruby Programming| Ruby on Rails by Example

How to remove an element from an array in Ruby Programming| Ruby on Rails by Example

How to check the type of a variable is Ruby| Ruby on Rails By Example

How to check if the variable is defined in Ruby with examples

How to Find the minimum and maximum values in an array and hash Ruby with examples

How to Generate Random number in Ruby with examples

How to Get current Unix timestamp or milliseconds since epoch Ruby Programming| Ruby on Rails by Example