-1

I have list like this:

list = ["test1","test2","test3"]

I want to assign three associated variables with values. Like:

test1_var = "test1"
test2_var = "test2"
test3_var = "test3"

I ran a loop like this and got an error:

list.each { |x| eval(x+"_var") = x}

What is the correct way to do this?

0

2 Answers 2

3

As far as I can tell, it is only possible to dynamically set instance variables and not local variables. So if this is inside a class of some sort, then this will work. If you absolutely don't want them as instance variables in then end, then just assign each to a local version.

list = ["test1","test2","test3"] 

list.each { |t| instance_variable_set("@#{t}_var".to_sym, t) }

Here is the documentation for instance_variable_set:

http://www.ruby-doc.org/core-1.9.3/Object.html#method-i-instance_variable_set

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

1 Comment

I just realized an alternative is to use binding with local_variable_set. ruby-doc.org/core-2.1.0/…
3

The block has a different scope of its own. So if you create a local variable within the block, it will not persist beyond the execution of list.each block. Also there are other restrictions as well.

This is almost impossible as per this blog post: http://blog.myrecipecart.com/2010/06/ruby-19-dynamic-creation-of-local.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.