Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the name of a Ruby class?

How can I get the class name from an ActiveRecord object?

I have:

result = User.find(1) 

I tried:

result.class # => User(id: integer, name: string ...) result.to_s # => #<User:0x3d07cdc>" 

I need only the class name, in a string (User in this case). Is there a method for that?

I know this is pretty basic, but I searched both Rails' and Ruby's docs, and I couldn't find it.

like image 682
andi Avatar asked May 05 '09 18:05

andi


People also ask

How do I find the class of an object in Ruby?

Use #is_a? to Determine the Instance's Class Name in Ruby If the object given is an instance of a class , it returns true ; otherwise, it returns false . #is_a also returns true if the object is an instance of any subclasses.

How do I know my Ruby type?

The proper way to determine the "type" of an object, which is a wobbly term in the Ruby world, is to call object. class . Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.

What does .class mean in Ruby?

What is a class in Ruby? Classes are the basic building blocks in Object-Oriented Programming (OOP) & they help you define a blueprint for creating objects. Objects are the products of the class.


1 Answers

You want to call .name on the object's class:

result.class.name 
like image 161
flicken Avatar answered Oct 04 '22 11:10

flicken