Ruby — use a string as a variable name to define a

2020-05-06 09:13发布

问题:

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?

回答1:

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.



回答2:

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 }


回答3:

You can use this hack:

names.each { |name| eval "def #{name}; []; end"  }