E
E
eldar_web2015-12-12 16:48:13
ruby
eldar_web, 2015-12-12 16:48:13

How can you create a variable from the value of a variable in Ruby?

There is for example a variable with the value str = 'auto'.
So can I, having this variable, create a new variable with its value, i.e., create an auto variable.
If so, how?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem Pyankov, 2015-12-12
@ibub1ik

If you have such a need, then your code = shit. But as an answer to the question, here:
stackoverflow.com/questions/17842765/how-do-i-dyna...

D
Dima, 2015-12-12
@MAXOPKA

In Ruby, you cannot dynamically declare a local variable.
But you can define, for example, a class instance variable.
Example:

str = 'auto'
eval "@#{str}= 'Такое то значение'"
p @auto

You can also define a method with the desired name, which will return a value. For example:
str = 'auto'
eval "def #{str}; 'Такое то значение' end"
p auto

BUT you don't need to do that. Especially if `str` is passed in from outside. It's easy to shoot yourself in the foot:
str = 'eval'
eval "def #{str}; 'Такое то значение' end"

Although, for example, in ActiveRecord methods with the names of table fields are dynamically created.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question