# Accessing local variables dynamically

**URL:** <https://www.ruby-forum.com/t/accessing-local-variables-dynamically/192506>\
**Category:** Ruby\
**Created:** [July 31, 2010, 8:14pm UTC](https://www.ruby-forum.com/t/accessing-local-variables-dynamically/192506 "2010-07-31T20:14:22Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ralphshnelvar](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e19adc/32.png) [@ralphshnelvar](https://www.ruby-forum.com/u/ralphshnelvar)\
**Post date:** [July 31, 2010, 8:14pm UTC](https://www.ruby-forum.com/t/accessing-local-variables-dynamically/192506/1 "2010-07-31T20:14:22Z")

</div>

I have a collection of variables named  
@a\_something, @c\_something, @f\_something, @y\_something, @z\_something

I want to do something like  
def some\_thing(one\_char)  
xxx = XXXX(’@’+one\_char+’\_something’)  
subr(xxx)  
end

I want  
some\_thing(‘c’)  
to have the same effect as  
subr(@c\_something)

What should XXXX be (should it be eval …?)?

This seems to work in 1.8. Will it work in 1.9?

I have read that the dynamic creation of variables in 1.9 is prohibited  
… but I’m not sure if this applies in my case since @c\_something  
(etc.) already exists.

---

<div class="post-metadata">

**Author:** ![ralphshnelvar](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e19adc/32.png) [@ralphshnelvar](https://www.ruby-forum.com/u/ralphshnelvar)\
**Post date:** [July 31, 2010, 8:58pm UTC](https://www.ruby-forum.com/t/accessing-local-variables-dynamically/192506/2 "2010-07-31T20:58:06Z")

</div>

Ralph S. wrote:

> I have a collection of variables named  
> @a\_something, @c\_something, @f\_something, @y\_something, @z\_something
> 
> I want to do something like  
> def some\_thing(one\_char)  
> xxx = XXXX(’@’+one\_char+’\_something’)  
> subr(xxx)  
> end
> 
> I want  
> some\_thing(‘c’)  
> to have the same effect as  
> subr(@c\_something)
> 
> What should XXXX be (should it be eval …?)?
> 
> This seems to work in 1.8. Will it work in 1.9?
> 
> I have read that the dynamic creation of variables in 1.9 is prohibited  
> … but I’m not sure if this applies in my case since @c\_something  
> (etc.) already exists.  
> instance\_variable\_get("@#{one\_char}\_something")

Though not knowing at all what you’re actually trying to accomplish,  
maybe you just want to use a hash instead?
