Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from string representing local variable [duplicate]

I have a local variable name as a string, and need to get its value.

variable = 22
"variable".to_variable?

How can I get the value 22 form the string?

like image 388
Lasse Sviland Avatar asked Jun 15 '15 08:06

Lasse Sviland


3 Answers

binding.local_variable_get("variable")
# => 22
like image 50
sawa Avatar answered Nov 02 '22 03:11

sawa


You can use eval.

variable = 22
eval("variable")
# => 22 

However eval can be nasty. If you dont mind declaring an instance variable, you can do something like this too:

@variable = 22
str = "variable"
instance_variable_get("@#{str}")
# => 22
like image 23
shivam Avatar answered Nov 02 '22 02:11

shivam


use eval() method:

variable = 22
eval "variable" #"variable".to_variable?
# => 22
like image 35
usmanali Avatar answered Nov 02 '22 03:11

usmanali