From: harryo@... (Harry Ohlsen) Date: 2001-04-23T20:40:04+09:00 Subject: [ruby-talk:14073] Re: RCR: getClassFromString method >You could simply use an eval: > > module ObjectSpace > def ObjectSpace.class(name) > eval(name) > end > end Thanks for that. I think that's much nicer than mine. >You might want to add some error checking: > > > module ObjectSpace > def ObjectSpace.class(name) > return nil if not (validClassname?(name) and eval(name).kind_of? Class) > > eval(name) > end > > def ObjectSpace.validClassname?(name) > name =~ /^[A-Z][a-zA-Z0-9]*$/ > end > end I'm not sure why you do the check on the validity of the class name. I assume it's because otherwise the eval would throw an exception? >If you are concerned about performance you could remove the doubled >eval, but then again if you are concerned about performance you should >implement it native anyway. In my case, I'm not all that worried about the performance, but I would guess other people might be. I'm using this to allow me to write "new Fred(...)" rather than "Fred.new(...)", and that's only because I keep making the mistake of using the former rather than the correct syntax, because I've been writing C++ and Java for far longer than I have Ruby. The other reason I wanted to do it was because I just wondered if I could. I should have known it was possible, because, after all, this is Ruby !!