dynamic object creation

K

Ken Tyler

sorry if i've missed something obvious

is there a way in ruby to dynamically create an object from a variable
that holds the object's name?

something that does object.create("some_object_name")
 
B

Ben Lovell

[Note: parts of this message were removed to make it a legal post.]

sorry if i've missed something obvious

is there a way in ruby to dynamically create an object from a variable
that holds the object's name?

something that does object.create("some_object_name")

Try:

Kernel.const_get("some_object_name")
 
T

Tim Hunter

Ken said:
sorry if i've missed something obvious

is there a way in ruby to dynamically create an object from a variable
that holds the object's name?

something that does object.create("some_object_name")

Assuming you mean "a variable that holds the class's name", check out
Module.const_get. This method takes a string and returns the value of
the constant having that name. Since the value of the constant Array is
the Array class object, we can get the Array class object like this:

cls = Module.const_get("Array")

And then call new on the class object to create a new array:

ary = cls.new
 
B

Brian Candler

Ken said:
sorry if i've missed something obvious

is there a way in ruby to dynamically create an object from a variable
that holds the object's name?

That doesn't make sense - if the object has a name then surely it
already exists?

Perhaps you wish to create an object where a variable holds the name of
the *class* you wish to create a new instance of. In that case:

klassname = "String"
klass = Object.const_get(klassname)
foo = klass.new

If the class name contains :: scope separator, then you need to split on
that first.

klass = klassname.split('::').inject(Object) { |base,item|
base.const_get(item)
}
 
K

Ken Tyler

thanks for all the responses

i'm just learning ruby so sometimes i don't know which end of the
screwdriver to grab
 
R

Robert Klemme

thanks for all the responses

i'm just learning ruby so sometimes i don't know which end of the
screwdriver to grab

Hint: if it hurts you got the wrong end. ;-)

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top