# Creating and naming variables dynamic

**URL:** <https://www.ruby-forum.com/t/creating-and-naming-variables-dynamic/196656>\
**Category:** Rails\
**Created:** [April 28, 2008, 5:06pm UTC](https://www.ruby-forum.com/t/creating-and-naming-variables-dynamic/196656 "2008-04-28T17:06:22Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tarscher](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/8491ac/32.png) [@Tarscher](https://www.ruby-forum.com/u/Tarscher)\
**Post date:** [April 28, 2008, 5:06pm UTC](https://www.ruby-forum.com/t/creating-and-naming-variables-dynamic/196656/1 "2008-04-28T17:06:22Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Tarscher](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/8491ac/32.png) [@Tarscher](https://www.ruby-forum.com/u/Tarscher)\
**Post date:** [April 28, 2008, 5:15pm UTC](https://www.ruby-forum.com/t/creating-and-naming-variables-dynamic/196656/2 "2008-04-28T17:15:18Z")

</div>

On 28 Apr 2008, at 16:05, Tarscher wrote:

> 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.

> 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

---

<div class="post-metadata">

**Author:** ![Tarscher](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/8491ac/32.png) [@Tarscher](https://www.ruby-forum.com/u/Tarscher)\
**Post date:** [April 28, 2008, 8:58pm UTC](https://www.ruby-forum.com/t/creating-and-naming-variables-dynamic/196656/3 "2008-04-28T20:58:25Z")

</div>

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
