Given a string find the matching class

Discussion in 'Ruby' started by James Byrne, Dec 9, 2008.

  1. James Byrne

    James Byrne Guest

    I have a situation where I desire to pass a string to a method that
    then:

    1. Capitalizes the the string value

    2. Finds a class by that name

    Something like:

    def findmyclass(m)
    find_class_by_name(m.capitalize)
    end

    Is this possible (surely) and if so, how is it done?

    Thanks
     
    James Byrne, Dec 9, 2008
    #1
    1. Advertisements

  2. James Byrne

    botp Guest

    1 class names are constants, thus
    1.1 they start w upcase, and
    1.2 are case sensitive

    2 you get the value of a quoted/stringified constant
    by using const_get

    3 you can then check the value returned by checking if it #is_a? Class

    eg,
    NameError: uninitialized constant YY

    now, if you want to find classes tucked in on other modules/classes,
    you'll have to scan the whole ObjectSpace; eg, looking for a class
    named "C" wc is in "A::B::C"...

    eg,
    Method
    MatchData
    Module
    M::MM
     
    botp, Dec 10, 2008
    #2
    1. Advertisements

  3. James Byrne

    James Byrne Guest

    botp wrote:

    Many thanks for this lucid explanation.
     
    James Byrne, Dec 10, 2008
    #3
    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.