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.
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?
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
🧮 Tags
Recent posts
Puppeteer Login Test example How to convert Double to Integer or Integer to double in Dart| Flutter By Example Best ways to fix 504 gateway time out in nodejs Applications Fix for Error No configuration provided for scss Multiple ways to List containers in a Docker with examplesRelated posts