Forum: Ruby Given a string find the matching class

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
James B. (Guest)
on 2008-12-10 00:13
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
botp (Guest)
on 2008-12-10 03:12
(Received via mailing list)
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
James B. (Guest)
on 2008-12-10 22:07
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.
This topic is locked and can not be replied to.