Getting class name without module

J

Jari Williamsson

Is there a method available to get only the class name, without getting
the module name prior to it? Alternatively, to get the class name within
the current name space context?

For example, self.class could return something like this:
MyModule::MyClass
(I would like to only get the "MyClass" part.)

Or do I have to resort to string manipulation/regexps?


Best regards,

Jari Williamsson
 
X

Xavier Noria

Is there a method available to get only the class name, without
getting the module name prior to it? Alternatively, to get the class
name within the current name space context?

For example, self.class could return something like this:
MyModule::MyClass
(I would like to only get the "MyClass" part.)

Or do I have to resort to string manipulation/regexps?

Indeed, you do it by hand, something like this:

name.split('::').last || ''

-- fxn
 
I

irio.musskopf

Em terça-feira, 12 de fevereiro de 2008 10h05min31s UTC-2, Jari Williamsson escreveu:
Is there a method available to get only the class name, without getting
the module name prior to it? Alternatively, to get the class name within
the current name space context?

For example, self.class could return something like this:
MyModule::MyClass
(I would like to only get the "MyClass" part.)

Or do I have to resort to string manipulation/regexps?


Best regards,

Jari Williamsson



Em terça-feira, 12 de fevereiro de 2008 10h05min31s UTC-2, Jari Williamsson escreveu:
Is there a method available to get only the class name, without getting
the module name prior to it? Alternatively, to get the class name within
the current name space context?

For example, self.class could return something like this:
MyModule::MyClass
(I would like to only get the "MyClass" part.)

Or do I have to resort to string manipulation/regexps?


Best regards,

Jari Williamsson

If you are using ActiveSupport:

MyModule::MyClass.to_s.demodulize # => "MyClass"
 
R

Robert Klemme

Em terça-feira, 12 de fevereiro de 2008 10h05min31s UTC-2, Jari Williamsson escreveu:

irb(main):001:0> module X; class Y; end end
=> nil
irb(main):002:0> X::Y.name
=> "X::Y"
irb(main):003:0> X::Y.name.split(/::/).last
=> "Y"
irb(main):004:0> X::Y.name.split('::').last
=> "Y"

Cheers

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top