Given a string find the matching class

J

James Byrne

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
 
B

botp

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
 
J

James Byrne

botp wrote:

3 you can then check the value returned by checking if it #is_a? Class ...
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.
 

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

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top