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
or binding.local_variable_set
.
I would consider using hash
to store values.
You cannot dynamically define local variables in ruby, but you can dynamically define instance variables:
names = ['log_index', 'new_index']
names.each { |name| instance_variable_set("@#{name}", []) }
This gives you:
@log_index
=> []
@new_index
=> []
You can also dynamically access instance variable with instance_variable_get
:
names = ['log_index', 'new_index']
names.each { |name| puts instance_variable_get("@#{name}").inspect }
You can use this hack:
names.each { |name| eval "def #{name}; []; end" }