Dynamic object construction

Thanks guys! const_get() works like a charm.

My fault for typing class as the parameter name - that's what I get for
typing code frags from scratch without running them first in a language
I've been using for 12 hours :slight_smile:

-John

ยทยทยท

-----Original Message-----
From: Bill Atkins [mailto:batkins57@gmail.com]
Sent: Monday, April 18, 2005 11:24 PM
To: ruby-talk ML
Subject: Re: Dynamic object construction

If class is a a class name (a String):

@obj = Object.const_get(klass).new

Using "class" as a parameter name won't work - the standard is to use
"klass" instead.

Bill

On 4/18/05, John Lam <jlam@iunknown.com> wrote:

I'm trying to create a new object where the class of the object is
parameterized. My current solution is to use eval():

def create(class)

@obj = eval("#{class}.new()")

end

Is there a better way of doing this to avoid the hit of eval()?

Thanks,

-John

http://www.iunknown.com

--
Bill Atkins

Thanks guys! const_get() works like a charm.

If you're working with Rails, or just have the Active Support gem available, this pattern has been boiled down to klass.constantize.new().

ยทยทยท

--
David Heinemeier Hansson,
http://www.basecamphq.com/ -- Web-based Project Management
http://www.rubyonrails.org/ -- Web-application framework for Ruby
http://www.loudthinking.com/ -- Broadcasting Brain