Get the name of a Ruby class

Here's how you can go about getting the name of a class in Ruby

Earlier today I wanted to get the name of a class in Ruby.

The reason I needed this was because I was grabbing an object that was polymorphic so I didn’t really know what I was dealing with.

Here is how I did it with some help from ActiveSupport;

my_object.class.name.demodulize

my_object is the object that I was unsure about.

Calling class on it returns a Class object.

Calling name on that object returns the name of the class.

Calling demodulize is a nice way of removing any modules that happen to be before it (I didn’t need the module information and most of the times you won’t).

If you don’t want to rely on ActiveSupport you can do;

my_object.class.name.split('::').last


Recent posts View all

Ruby

Forcing a Rails database column to be not null

How you can force a table column to always have something in it with Rails

Writing Marketing

We've deleted an article's worth of unhelpful words

We've improved several pages across our site by removing words that add no value, and often detract from the article.