"Jim Weirich" <jweirich / one.net> wrote in message news:m2ofhx1lp7.fsf / skaro.access.one.net... > >>>>> "David" == David Corbin <dcorbin / imperitek.com> writes: > > David> At the moment, I'm having problem with #2. In Java, you > David> can do Class.forName("Foo") to see get a Class object for > David> class Foo. The ruby Class class doesn't seem to have this > David> capability. Please help > > Class names are constants. Top level class names are constants in > Object. You can use const_get to fetch the value. For example ... > > foo_class = Object.const_get("Foo") > > If "Foo" is not a class, you will get a NameError in const_get. > > If the class is nested in a module (e.g. Foo::Bar), you have to do a > little more work. The following code will return the class object for > any class name (including nested classes), or will return nil if there > is no match. > > def class_for(class_name) > names = class_name.split("::") > result = Object > names.each { |n| > result = result.const_get(n) > } > result > rescue NameError > nil > end > > You can also use eval to get a constant value, but passing unvalidated > strings to eval is kinda risky. After a recent battle with a small bucklet involving file names it got me thinking what happens if you try your code with absolute path like "::A::B" - it's a no brainier adjusting your code to deal with this possibility however if ''.intern were a valid ``Constant Symbol'' we could write --- Object.const_set ''.intern , Object # your code ... here is an implementation of this N(ot)A(n)RCR. class String Null = '' def null? eql? Null end end class Symbol Null =''.intern def null? eql? Null end private alias old_intern intern public def intern unless null? old_intern else # feeble attempt of name mangling :GLOBAL_NULL_69_96__ end end end class Module private alias old_const_get const_get # also ``alias const_set'', etc. def const_get (sym_or_str) unless null? old_const_get(sym_or_str) else old_const_get(:GLOBAL_NULL_69_96__) end end end --- /Christoph