Dynamic object construction

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

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

@obj = Object.const_get(klass).new

does this work if klass == My::Namespace::Klass ?

-g.

George Moschovitis wrote:

> @obj = Object.const_get(klass).new

does this work if klass == My::Namespace::Klass ?

Assuming you mean the string value

  klass = "My::Namespace::Klass"

The answer is No. One has to do:

  klass = "Klass"
  @obj = My::Namespace.const_get(klass).new

The namespace issue is problematic. One alternative is in Ruby Facets:

  require 'facet/object/constant'

  klass == "My::Namespace::Klass"
  @obj = constant(klass).new

T.

The answer is No. One has to do:
klass = "Klass"
@obj = My::Namespace.const_get(klass).new

I was expecting the negative answer :wink:

One alternative is in Ruby Facets

Interesting, I 'll see how that works...

-g.

Or the ever popular

klass.split('::').inject(Object) {|parent, name| parent.const_get(name)}

···

On 4/20/05, Trans <transfire@gmail.com> wrote:

Assuming you mean the string value
  klass = "My::Namespace::Klass"
The answer is No. One has to do...