From: harryo@... (Harry Ohlsen) Date: 2001-04-23T06:40:09+09:00 Subject: [ruby-talk:14041] Re: RCR: getClassFromString method On Sun, 22 Apr 2001 21:24:52 GMT, ptkwt@shell1.aracnet.com (Phil Tomson) wrote: >It would be nice to have a function that returns a class type given a >string that names that class. I realize that this is doable already in at >least a couple of different ways - you can use the each_object method in >ObjectSpace to iterate through all of the classes till you find the one >you need, or you can use const_get in Modules, (at least that's where I >think it is), but none of those ways is intuitive and easy to figure out >for newbies. Indeed. I did this just yesterday. I added a routine to ObjectSpace, as you suggest. In case it's of interest to you (it sounds like you'd have no problem writing it yourself, but why bother if someone else has already done it), here's my code. By the way, I asked the question yesterday as to where I should put code that I want executed every time the interpreter is started, so that I don't have to do a "require 'xxx'" in each module where I want to use this. So far, I haven't received any advice. ############################################ module ObjectSpace # Find the definition of the specified class ... def ObjectSpace.findClass(name) # Use each_object() to find all objects of # type "Class" ... each_object(Class) do |c| # If this Class object has the required name, # it's the one we want, so just return it ... if c.name == name.to_s return c; end end # We didn't find a class of the specified name, so # just return nil ... return nil; end end