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

user3156792
  • 79
  • 1
  • 7

2 Answers2

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

SreekanthGS
  • 988
  • 5
  • 12
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

KenneyE
  • 353
  • 1
  • 12
  • 1
    I just realized an alternative is to use binding with `local_variable_set`. http://www.ruby-doc.org/core-2.1.0/Binding.html#method-i-local_variable_set – KenneyE Apr 29 '14 at 16:47