From: Rob Biedenharn Date: 2007-06-16T00:14:24+09:00 Subject: Re: Dynamic Class Initialization On Jun 15, 2007, at 10:41 AM, Enrique Comba Riepenhausen wrote: > Hi Peer, > > On Friday, June 15, 2007, at 04:36PM, "Peer Allan" > wrote: >> Hi all, >> I know this can be done, but I can't find out how to do it. I have a >> string with the name of the class that I want to initialize, but >> how do >> I do it? >> >> This is what I tried, >> >> class = "Product" >> product = class.new >> >> Obviously this does not work or I wouldn't be asking :) So, how >> do I do >> this? >> >> Peer > > Try this: > > clazz = Object.const_get("Product") > product = clazz.new > > The word class is a reserved word so yu should use something > different... > > Cheers, > > Enrique # from Jim Weirich (based on email correspondence) def constantize(camel_cased_word) camel_cased_word. sub(/^::/,''). split("::"). inject(Object) { |scope, name| scope.const_get(name) } end Actually, Jim answered this question twice, once directly and once in a post to our local users group with nearly identical code, but clearly typed in ad hoc both times. If you need to deal with something like ActiveRecord::Base, the simple form doesn't work: >> Object.const_get "ActiveRecord::Base" NameError: wrong constant name ActiveRecord::Base from (irb):1:in `const_get' from (irb):1 >> "ActiveRecord::Base".split('::').inject(Object) {|scope,name| scope.const_get(name)} => ActiveRecord::Base -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com