Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Ruby pure class name without parent name, any direct method for it?

Tags:

ruby

I often need to get the pure class name of an object, as code below:

class Foo
    class Bar

    end
end
obj = Foo::Bar.new
puts obj.class.name  # It shows "Foo::Bar", while what I want is just "Bar"

I know it can be done by obj.class.name.split('::').last, but, shouldn't be there a method just return "Bar" ?

like image 678
brookz Avatar asked Mar 19 '23 09:03

brookz


1 Answers

In vanilla Ruby, I'm pretty sure class.name.split('::').last is the best way to go. But if you happen to be using ActiveSupport (if you're on Rails, this library will be loaded) there is an inflector called demodulize.

class Foo
    class Bar
    end
end
obj = Foo::Bar.new
puts obj.class.name.demodulize # => Bar
like image 88
thomax Avatar answered Mar 23 '23 00:03

thomax