ironsand ironsand - 1 month ago 14
Ruby Question

How to get only class name without namespace

There is a class like this.

module Foo
class Bar
end
end


And I want to get the class name of
Bar
without
Foo
.

bar = Foo::Bar.new
bar.class.to_s.match('::(.+)$'){ $1 }


I could get the class name by this code, but I don't think this is a best way to get it.

Is there better way to get the name of class without namespace?

Answer

The canonical way to do this is to invoke Object#class and Module#name. For example:

bar.class.name.split('::').last
#=> "Bar"
Comments