Given a string find the matching class


#1

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


#2

On Wed, Dec 10, 2008 at 6:06 AM, James B. removed_email_address@domain.invalid
wrote:

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?

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,

Object.const_get(“XX”).is_a? Class
=> true
Object.const_get(“Xx”).is_a? Class
=> true
Object.const_get(“YY”)
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,

ObjectSpace.each_object(Class).each {|x| p x if x.name =~ /^M/ }
Method
MatchData
Module
M::MM


#3

botp wrote:

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

Object.const_get(“XX”).is_a? Class
=> true
Object.const_get(“Xx”).is_a? Class
=> true
Object.const_get(“YY”)
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”…

ObjectSpace.each_object(Class).each {|x| p x if x.name =~ /^M/ }
Method
MatchData
Module
M::MM

Many thanks for this lucid explanation.