1

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?

2
  • 2
    What do you mean by string in a variable name? Commented Sep 1, 2017 at 8:40
  • 1
    Where does the index array come from? Why don't you just assign the variables manually via log_index = [] and new_index = []? What are you trying to achieve? Commented Sep 1, 2017 at 8:53

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree with the hash mentality in this case even something as simple as index.each_with_object(Hash.new {|h,k| h[k] = []}) {|i,obj| obj[i]}
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 }

Comments

0

You can use this hack:

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

1 Comment

In this case define_method seems more appropriate than eval. That being said it will always return an empty Array which does not seem very useful since I assume the intent is to store information in it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.