# How to Get an Object's Class Name in Rails

*Published on September 11, 2022*

---


Let's say you want an object's class name in Ruby. You'd write something like this:

```ruby
module Bank
  class Account
  end
end

irb(main):005:0> account = Bank::Account.new
=> #<Bank::Account:0x0000000106115b00>
irb(main):006:0> account.class.name
=> "Bank::Account"
irb(main):008:0> account.class.name.split("::").last
=> "Account"
```

In Rails, you can use the&nbsp;[`demodulize`](https://api.rubyonrails.org/classes/String.html#method-i-demodulize)&nbsp;method on the string, which is added by Active Support. It removes the module part from the constant expression in the string.

```ruby
irb(main):014:0> account.class.name.demodulize
=> "Account"
```

Internally, this method calls the&nbsp;`demodulize`&nbsp;class method on the&nbsp;`ActiveSupport::Inflector`&nbsp;class, passing itself as the argument.

```ruby
# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 166
def demodulize
  ActiveSupport::Inflector.demodulize(self)
end
```

The&nbsp;`Inflector.demodulize`&nbsp;function does the same thing.

```ruby
demodulize('ActiveSupport::Inflector::Inflections') # => "Inflections"
demodulize('Inflections')                           # => "Inflections"
demodulize('::Inflections')                         # => "Inflections"
demodulize('')                                      # => ""
```

However, its internal implementation is different than our simple version above.

```ruby
# File activesupport/lib/active_support/inflector/methods.rb, line 228
def demodulize(path)
  path = path.to_s
  if i = path.rindex("::")
    path[(i + 2)..-1]
  else
    path
  end
end
```

After converting the&nbsp;`path`&nbsp;argument to a string, it gets the index of the last occurrence of&nbsp;`::`&nbsp;using Ruby's&nbsp;[`rindex`](https://ruby-doc.org/core-3.1.1/String.html#method-i-rindex)&nbsp;function. If it exists, then it returns the remaining substring. Otherwise, it returns the original string. The&nbsp;`array[n..-1]`&nbsp;expression returns the substring from&nbsp;`n`&nbsp;to the last character in the string.

So these are a few ways to get an object's class name in Ruby and Rails. I hope it helped.

