Getting class name without module

Discussion in 'Ruby' started by Jari Williamsson, Feb 12, 2008.

  1. 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
     
    Jari Williamsson, Feb 12, 2008
    #1
    1. Advertisements

  2. Jari Williamsson

    Xavier Noria Guest

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

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

    -- fxn
     
    Xavier Noria, Feb 12, 2008
    #2
    1. Advertisements

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


    Em terça-feira, 12 de fevereiro de 2008 10h05min31s UTC-2, Jari Williamsson escreveu:
    If you are using ActiveSupport:

    MyModule::MyClass.to_s.demodulize # => "MyClass"
     
    irio.musskopf, Dec 4, 2012
    #3
  4. 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
     
    Robert Klemme, Dec 5, 2012
    #4
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.
Similar Threads
There are no similar threads yet.
Loading...