creating and naming variables dynamic

Hi all,

I want to create a variable dynamic. I have defined some classes and depending on data I get from a database I need to construct an object eg:

now I do

if type=="car"   variab = Car.new elsif type="boat"   variab = Boat.new end

can I do something like variab = Instance.new(type)

Following this: can I give dynamic variablenames? now I do if type=="car"   car_string = Car.new elsif type="boat"   boat_string = Boat.new end

can I do something like dynamicpart_string = Instance.new(type)

Regards, Stijn

Hi all,

I want to create a variable dynamic. I have defined some classes and depending on data I get from a database I need to construct an object eg:

now I do

if type=="car" variab = Car.new elsif type="boat" variab = Boat.new end

can I do something like variab = Instance.new(type)

Not quite. but if you can construct a string containing the class
name, the some_string.constantize.new should work. I've no idea what you're doing, but activerecord's single table
inheritance (STI) may be of interest.

Following this: can I give dynamic variablenames? now I do if type=="car" car_string = Car.new elsif type="boat" boat_string = Boat.new end

can I do something like dynamicpart_string = Instance.new(type)

not cleanly (and my instinct is that if you do this you will be
entering a world of pain)

Fred

Hi Stijn,

for dynamic variable names take a look at instance_variable_set:

inst_var = "wallyworld" instance_variable_set("@" + inst_var, value)

which assigns some value, 'value' to the variable '@wallyworld'

and instance_variable_get:

value = instance_variable_get("@" + inst_var)

which retrieves the value 'value' from the variable '@wallyworld'

Regards

Walter