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

2020-05-06 09:22发布

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?

3条回答
The star\"
2楼-- · 2020-05-06 09:40

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.

查看更多
何必那么认真
3楼-- · 2020-05-06 09:55

You can use this hack:

names.each { |name| eval "def #{name}; []; end"  }
查看更多
老娘就宠你
4楼-- · 2020-05-06 10:04

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 }
查看更多
登录 后发表回答