I have an array of strings:
names = ['log_index', 'new_index']
What I want to do is to create variables from the names:
names.each { |name| name = [] } # obviously it does not do what I want
Those variables are not declared before anywhere in the code.
How could I do that?
There is no way to define new local variables dynamically in Ruby.
It was possible in Ruby 1.8 though with
eval 'x = 2'
.You can change an existing variable with
eval
orbinding.local_variable_set
.I would consider using
hash
to store values.You can use this hack:
You cannot dynamically define local variables in ruby, but you can dynamically define instance variables:
This gives you:
You can also dynamically access instance variable with
instance_variable_get
: