0

I am learning ruby and wondering if it is possible to create a var from a variable combined with a string.

a = "variable"
a+"_name" = []
variable_name => []

Thanks, CG

3 Answers 3

4

You can do this easily with an instance variable as such:

>> a = "variable"
=> "variable"
>> instance_variable_set(:"@#{a}_name", [])
=> []
>> @variable_name
=> []

If you're curious about why this is easier to do with an ivar, read up about Ruby variable binding and scoping rules.

Sign up to request clarification or add additional context in comments.

2 Comments

What is the # doing in this @#{a}_name and is the : setting it as a symbol?
@CoryGwin: The leading : makes it a symbol, the #{} inside the double quoted string is just normal string interpolation.
3

But don't do that. So much easier and better to use a hash:

variable = {}
variable['name'] = []

or

vars = {}
vars[["variable", "name"]] = []

3 Comments

Yeah hash is strongly recommended when comes to undelcared var or methods. It can take care of it
I take it this is for name spacing? What if it is part of a class, or I guess object instance?
THis question has been asked before, and I have yet to see a good reason to do it. Php had some sort of variable interpolation, and I suspect most of the questions like this are people bringing that abomination into ruby... ;)
1

Incase you still want to do with variables:

>> a = 'variable'
 => "variable" 
>> eval(a + '_name=[]')
 => [] 
>> variable_name
 => [] 

Hope you understand how evil eval is!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.